题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解决方法1
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
return abs(TreeDepth(pRoot->left)-TreeDepth(pRoot->right))<=1 &&
IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot)//求二叉树的深度
{
if(!pRoot) return 0;
return 1+max(TreeDepth(pRoot->left),TreeDepth(pRoot->right));
}
};
解决方法2
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
//这里只需判断是否节点深度相差都不超过1即可,无需判断是中序遍历是递增的
if(!pRoot) return true;
int depth=0;
return IsBalanced(pRoot,&depth);
}
bool IsBalanced(TreeNode* p,int *depth){//一边遍历一遍计算
if(!p) {*depth=0; return true;}
int left=0,right=0;
if(IsBalanced(p->left,&left) && IsBalanced(p->right,&right)){
int diff=abs(right-left);
if(diff<=1){*depth=1+max(left,right);return true;}
}
return false;
}
};