平衡二叉树的判断

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。


/*方法一:自顶向下;从根节点向下检查各节点的子树是否都满足平衡二叉树的条件,遍历整个二叉树。
         递归过程中多次重复计算子树的深度,效率较低.
*/

/*
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;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值