#判断一个树是二叉平衡树
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL)
return 1;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
int diff=left-right;
if(diff>1 || diff<-1)
return 0;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
private:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
int left=TreeDepth(pRoot->left);
int right=TreeDepth(pRoot->right);
return (left>right?left:right)+1;
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return isBalanced_Solution(pRoot,depth);
}
private:
bool isBalanced_Solution(TreeNode* pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return 1;
}
int left=0,right=0;
if(isBalanced_Solution(pRoot->left,left) && isBalanced_Solution(pRoot->right,right)){
int diff=left-right;
if(diff<=1 && diff>=-1){
depth=1+(left>right?left:right);
return true;
}
}
return 0;
}
};
比较,第一种方法是递归求深度,从上往下判断是否平衡,有很多重复计算。第二种方法则是后序遍历,用一个变量保持深度,从下往上判断,只计算了一次。这个原因就在于下面平衡了,只需判断上面就可以,而上面平衡下面确不一定平衡,所以自下而上更好。
因篇幅问题不能全部显示,请点此查看更多更全内容