LeetCode----Balanced Binary Tree

95 篇文章 0 订阅
93 篇文章 0 订阅
本文介绍了如何解决LeetCode上的‘Balanced Binary Tree’问题,定义一个高度平衡的二叉树为任意节点的两个子树深度差不超过1。通过递归方法,检查每个子树是否满足平衡条件,并返回子树的最大高度。如果树为空,也被视为平衡。文章还提供了相关的Python代码实现。
摘要由CSDN通过智能技术生成

Balanced Binary Tree

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.


分析:

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

使用递归判断,在递归中需要做到两点,第一点,如果当前子树不满足平衡二叉树的性质,而返回False;第二点,如果当前子树满足平衡二叉树,则返回当前子树的高度。

另外,如果树为空,也是平衡二叉树。


代码:

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        isAVL = self.traverse(root)
        return True if isAVL else False

    def traverse(self, root):
        if root:
            l_high = self.traverse(root.left)
            r_high = self.traverse(root.right)
            if not l_high or not r_high:
                return False
            if abs(l_high - r_high) > 1:
                return False
            return max(l_high, r_high) + 1
        return 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值