[LeetCode 110] - 平衡二叉树 (Balanced Binary Tree)

问题

给出一棵二叉树,判断它是否在高度上是平衡的。

对于本问题,高度上平衡的二叉树定义为:每个节点的两棵子树的深度差永远不大于1的一棵二叉树。

 

初始思路

根据定义,思路应该比较直接:递归计算每个节点左右子树的深度,只要发现一次深度差大于1的情况,即可终止递归返回不平衡的结果。最终代码如下:

 1 class Solution
 2     {
 3     public:
 4         bool isBalanced(TreeNode *root)
 5         {
 6             if(!root)
 7             {
 8                 return true;
 9             }
10             
11             isBalanced_ = true;
12             
13             GetDepth(root);
14             
15             return isBalanced_;
16         }
17         
18     private:
19         int GetDepth(TreeNode* node)
20         {
21 //已经不平衡后不需要再继续了,返回的深度也没用了,随便返回一个0即可
22             if(!isBalanced_)
23             {
24                 return 0;
25             }
26             
27             if(!node->left && !node->right)
28             {
29                 return 1;
30             }
31             
32 //当前节点贡献1的深度
33             int left  = 1;
34             int right = 1;
35             
36             if(node->left)
37             {
38                 left += GetDepth(node->left);
39             }
40             
41             if(node->right)
42             {
43                 right += GetDepth(node->right);
44             }
45             
46             if(left > right + 1 || right > left + 1)
47             {
48                 isBalanced_ = false;
49                 
50                 return 0;
51             }
52             
53             return left > right ? left : right;
54         }
55         
56         bool isBalanced_;
57         
58     };
isBalanced

 

posted @ 2013-08-01 00:05  Shawnone  阅读(343)  评论(0编辑  收藏  举报