leetcode 110-判断一棵树是否为平衡二叉树 #算法#

25 篇文章 1 订阅

原题如下

Given a binary tree, determine if it is height-balanced.
给出一棵二叉树,判断它是否高度平衡。
For this problem, a height-balanced binary tree is defined as:
高度平衡二叉树定义为:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
任何节点的两棵子树的深度差不能大于一。

换个说法就是,左右子树的高度(深度)差不能超过一并且左右子树也是平衡二叉树。

思路

首先需要计算一棵树的深度,一棵树的深度为其左右子树的较大深度加上一,左右子树的深度也可以用同样的方法计算出,可以用递归实现,终止条件是根节点为空时深度为0;
有了深度之后,就可以比较某一节点的左右子树的深度差是否小于等于1,并要求左右子树也是平衡树,同样可以用递归实现,终止条件是空树是平衡树。

代码

class Solution {
public:
    int depth(TreeNode* root){
        if(root == NULL) return 0;
        int leftDepth = depth(root->left);
        int rightDepth = depth(root->right);
        return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
    }
    
    bool isBalanced(TreeNode* root) {
        if(root == NULL) return true;
        return abs(depth(root->left) - depth(root->right)) <= 1 
            && isBalanced(root->left) 
            && isBalanced(root->right);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值