题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
分析:平衡二叉树的左右子树都是平衡二叉树,平衡二叉树的左右子树高度差不超过1。最直接的想法就是递归调用算出来每一个子树的高度然后作差去比,但是那样的话会重复访问很多次结点,所以不推荐。如果用后序遍历的话,每个结点只需要遍历一次就可以。
代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int Depth=0;
return IsBalanced(pRoot,&Depth);
}
bool IsBalanced(TreeNode* pRoot,int* pDepth){
if(pRoot==NULL){
*pDepth=0;
return true;
}
int left=0,right=0;
if(IsBalanced(pRoot->left,&left) && IsBalanced(pRoot->right,&right)){
int diff=left-right;
if(diff<=1 && diff>=-1){
*pDepth=1+(left>right?left:right);
return true;
}
}
return false;
}
};