题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
/*方法一:自顶向下;从根节点向下检查各节点的子树是否都满足平衡二叉树的条件,遍历整个二叉树。
递归过程中多次重复计算子树的深度,效率较低.
*/
/*
class Solution{
public:
bool IsBalanced_Solution(TreeNode* pRoot)
{
if(!pRoot) return true;
int leftd=GetDepth(pRoot->left);
int rightd=GetDepth(pRoot->right);
if(abs(leftd-rightd)>1) return false;
return (IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right));
//每次IsBalanced_Solution递归的时候又会重新利用GetDepth递归计算子树的深度,
//包含多次重复计算,主要是没有用变量记录子树的深度。
}
int GetDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int ld=GetDepth(pRoot->left);
int rd=GetDepth(pRoot->right);
return ((ld>rd)?ld:rd)+1;
}
};
*/
/*方法二:自底向上;从叶子结点向上检查节点的子树是否都满足平衡二叉树的条件,递归过程中用变量depth记录二叉树的深度累加,
避免为了求解二叉树的深度而进行多次递归过程,效率有所提高。
*/
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot, depth);
}
bool IsBalanced(TreeNode* pRoot, int& depth)
{
if(!pRoot)
{
depth=0;
return true;
}
int leftd=0, rightd=0;
if(IsBalanced(pRoot->left,leftd)&&IsBalanced(pRoot->right,rightd))
{
//利用IsBalanced的递归,从叶子结点向上检查各个节点是否满足平衡二叉树的要求
if(abs(leftd-rightd)>1) return false;
depth=(leftd>rightd)?leftd+1:rightd+1;
//用depth记录二叉树向上查询的过程中,树的深度的累加过程,不用再进行递归单独求每个子树的深度
return true;
}
return false;
}
};