题目链接
题目要求:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
这道题难度还好。具体程序(16ms)如下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode* root) { 13 return isBalancedSub(root); 14 } 15 16 bool isBalancedSub(TreeNode *tree) 17 { 18 if(!tree) 19 return true; 20 if(abs(getHeight(tree->left) - getHeight(tree->right)) > 1) 21 return false; 22 return isBalancedSub(tree->left) && isBalancedSub(tree->right); 23 } 24 25 int getHeight(TreeNode *tree) 26 { 27 if(!tree) 28 return 0; 29 30 int m = getHeight(tree->left); 31 int n = getHeight(tree->right); 32 return (m > n) ? m + 1 : n + 1; 33 } 34 };
时间: 2024-11-03 01:25:55