剑指offer——平衡二叉树

题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
方法一:
在判断左右子树是否为平衡二叉树的同时也在计算当前子树的深度depth;
之后返回根节点后,如果左右子树深度之差大于1,则返回false,否则返回左右子树的判断结果。

class Solution {
    
    bool JudgeBalance(TreeNode* pRoot, int &depth) {
        if (!pRoot)
            return true;
        int leftDepth = 0;
        int rightDepth = 0;
        
        bool leftJudge = JudgeBalance(pRoot->left, leftDepth);
        bool rightJudge = JudgeBalance(pRoot->right, rightDepth);
        depth = (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
        if (abs(leftDepth - rightDepth) <= 1)
            return leftJudge && rightJudge;
        else 
            return false;
    }
    
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth = 0;
        return JudgeBalance(pRoot, depth);
    }
};

方法二:
从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。

class Solution {
    
    int GetDepth(TreeNode* pRoot) {
        if (!pRoot)
            return true;
        int leftDepth = GetDepth(pRoot->left);
        if (leftDepth == -1)
            return -1;
        int rightDepth = GetDepth(pRoot->right);
        if (rightDepth == -1)
            return -1;

        return abs(leftDepth-rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
    }
    
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return GetDepth(pRoot) != -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值