[剑指Offer]判断一棵树为平衡二叉树(递归)

题目链接

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=0&tqId=0&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题意

判断一棵树是否为平衡二叉树

思路

法一,定义版:按定义,自上而下遍历树,会有重复计算。
法二,优化版:自下而上遍历树,若不平衡则返回-1,至多遍历树一遍。

相关知识

平衡二叉树:或空树,或根结点左右子树高度差<=1,且左右子树也为平衡二叉树。

代码

定义版

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==NULL){return true;}
        else if(abs(getDepth(pRoot->left)-getDepth(pRoot->right))<=1){
            return true;
        }
        return false;
    }
private:
    int getDepth(TreeNode* pRoot){
        if(pRoot==NULL){return true;}
        else return max(getDepth(pRoot->left),getDepth(pRoot->right))+1;
    }
};

优化版

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return getDepth(pRoot)!=-1;
    }
private:
    int getDepth(TreeNode* pRoot){
        if(pRoot==NULL){return 0;}
        else{
            int left=getDepth(pRoot->left);
            if(left==-1){return -1;}
            
            int right=getDepth(pRoot->right);
            if(right==-1){return -1;}
            
            if(abs(right-left)>1){return -1;}
            else{return max(left,right)+1;}
        }
    }
};

posted on   coding_gaga  阅读(570)  评论(0编辑  收藏  举报

编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示