Balanced Binary Tree

题目:

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则当前树平衡,否则失衡;
  2. 不平衡->当前树不平衡;

代码如下,

 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了。

posted @ 2013-11-16 18:33  月窟仙人  阅读(129)  评论(0编辑  收藏  举报