题目:
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.
思路比较简单:
先看左右子树:
- 平衡->看左右子树的高度差,不超过1则当前树平衡,否则失衡;
- 不平衡->当前树不平衡;
代码如下,
1 bool isBalanced(TreeNode *root) { 2 int h=0; 3 return isBalanced(root,&h); 4 } 5 bool isBalanced(TreeNode *root, int *height){ 6 if(root==NULL) return true; 7 int lheight=0,rheight=0; 8 if(isBalanced(root->left,&lheight)&&isBalanced(root->right,&rheight)){ 9 int delta = lheight-rheight; 10 if(delta<2&&delta>-2){ 11 *height=(lheight>rheight?lheight:rheight)+1; 12 return true; 13 } 14 } 15 return false; 16 }
其中第11行的括号第一次提交的时候没加,导致+1与三元操作符的最后一个操作数结合产生错误了。加个括号就PASS了。