题目如下
思路与代码
自上而下
就是从根节点找左右树的最大深度,然后比较。接着再找子树的左右树,
这个听着就挺浪费资源的吧
我们看看代码实现,多说无益,一看便知。
class Solution {
public:
int tree_depth(TreeNode *root){
if(!root) return 0;
if((!(root->left))&&(!(root->right))) return 1;
int deep_left=tree_depth(root->left)+1;
int deep_right=tree_depth(root->right)+1;
return (deep_left>deep_right)?deep_left:deep_right;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
int ldeep=tree_depth(pRoot->left);
int rdeep=tree_depth(pRoot->right);
if(abs(ldeep-rdeep)>1) return false;
return (IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right));
}
};
自下而上
自下而上的方法更好,因为中间相当于设计了剪枝!
==一旦出现子树的左右不平衡,马上止损,出结果 ==
class Solution {
public:
int depth(TreeNode *root){
if(root == NULL)return 0;
int left = depth(root->left);
if(left == -1)return -1; //如果发现子树不平衡之后就没有必要进行下面的高度的求解了
int right = depth(root->right);
if(right == -1)return -1;//如果发现子树不平衡之后就没有必要进行下面的高度的求解了
if(abs(left - right)>1)//注意这里的判断是子树的左右哦!!!
return -1;
else
return 1+(left > right?left:right);
}
bool IsBalanced_Solution(TreeNode* pRoot) {
return depth(pRoot) != -1;
}
};