剑指Offer:平衡二叉树

剑指Offer:平衡二叉树


题目:

在这里插入图片描述

分析

平衡二叉树:它是一棵空树,或者它的左右子树的高度差的绝对值不超过 1,并且它的左右子树也是平衡二叉树。

解法一

我能想到的最直接的递归解法如下:

class Solution {
public:
    map<TreeNode*, int> node_deepth;
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == nullptr) return true;
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)
            && abs(getHeight(pRoot->left) - getHeight(pRoot->right)) <= 1;
    }
    int getHeight(TreeNode* node) {
        if (node == nullptr) return 0;
        if (node_deepth.find(node) != node_deepth.end()) return node_deepth[node];
        node_deepth[node] = 1 + max({getHeight(node->left), getHeight(node->right)});
        return node_deepth[node];
    }
};

加了一个 node_deepth 表,避免重复求高度。

解法二

向底向下方法:

  1. 在求高度的时候判断是否是平衡二叉树,如果不是,则高度返回 -1。
  2. 如果左右子树中有一个返回了 -1,这个树的高度就是 -1。
  3. 如果根结果返回的是 -1,则不是平衡二叉树,如果是一个正常的高度,那就是平衡二叉树。
class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return getDeepth(pRoot) != -1;
    }
    int getDeepth(TreeNode* node) {
        if (node == nullptr) return 0;
        int leftDeepth = getDeepth(node->left);
        int rightDeepth = getDeepth(node->right);
        if (leftDeepth == -1 || rightDeepth == -1 || abs(leftDeepth - rightDeepth) > 1)
            return -1;
        return max({leftDeepth, rightDeepth}) + 1;
    }
};

进一步改进一下:把上面代码的顺序变一下,就相当于加了个剪枝。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return getDeepth(pRoot) != -1;
    }
    int getDeepth(TreeNode* node) {
        if (node == nullptr) return 0;
        int leftDeepth = getDeepth(node->left);
        if (leftDeepth == -1) return -1;
        int rightDeepth = getDeepth(node->right);
        if (rightDeepth == -1) return -1;
        if (abs(leftDeepth - rightDeepth) > 1) return -1;
        return max({leftDeepth, rightDeepth}) + 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值