程序员面试金典——4.1二叉树平衡检查

本文介绍了两种判断二叉树是否平衡的有效方法。第一种方法使用两次递归分别计算左子树和右子树的深度;第二种方法源自《剑指offer》,通过优化减少重复计算,提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Solution1:

转载自:https://www.nowcoder.com/profile/7699453/codeBookDetail?submissionId=15222689
这种用两个递归的方法还是第一次见,重点学习下depth的写法!
20181010整理代码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class Balance {
public:
    bool isBalance(TreeNode* root) {
        // write code here
        if(root == NULL)
            return true;
        int diff = depth(root->left) - depth(root->right);
        if(abs(diff) > 1)
            return false;
        else
            return isBalance(root->left) 
                   && isBalance(root->right);
    }
    
     int depth(TreeNode *root) {
        if(!root)
            return 0;
        int left = depth(root->left);
        int right = depth(root->right);
        return max(left, right) + 1;
    }
};

原答案

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class Balance {
public:
    bool isBalance(TreeNode* root) {
        // write code here
        if(root == NULL)
            return true;
        int diff = depth(root->left) - depth(root->right);
        if(abs(diff) > 1)
            return false;
        else
            return true;
        return isBalance(root->left) && isBalance(root->right);
    }
    
     int depth(TreeNode *root) {
        if(root == NULL)
            return 0;
        int left = depth(root->left);
        int right = depth(root->right);
        return (left > right)? (left + 1):(right + 1);
    }
};

Solution2:

《剑指offer》上的思路更好,时间复杂度更低。参考链接:
https://blog.csdn.net/Allenlzcoder/article/details/79685413

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值