Python 确定二叉树是否平衡

Python 确定二叉树是否平衡,python,binary-tree,Python,Binary Tree,基本上,此代码用于确定二叉树是否高度平衡。这是我的密码 class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def isBalanced(self, root): # write your code here if root is None:

基本上,此代码用于确定二叉树是否高度平衡。这是我的密码

class Solution:
    """
    @param root: The root of binary tree.
    @return: True if this Binary tree is Balanced, or false.
    """
    def isBalanced(self, root):
        # write your code here
        if root is None:
            return

        left_height = self.findHeight(root.left)
        right_height = self.findHeight(root.right)
        print(root.val,left_height,right_height)
        self.isBalanced(root.left)
        self.isBalanced(root.right)
        if abs(left_height - right_height) > 1:
            return False
        return abs(left_height - right_height) <= 1

    def findHeight(self, root):
        if root is None:
            return 0
        left_height = self.findHeight(root.left)
        right_height = self.findHeight(root.right)
        height = max(left_height, right_height) + 1
        return height

对于节点2,
left_height
为2,其
right_height
为0,差值大于1,应返回
False
。但是这段代码返回
True
,我感到困惑。

您的代码只检查树顶的高度是否正确。您需要考虑子树的结果

这个

应该是这个吗

return (
    self.isBalanced(root.left) and
    self.isBalanced(root.right) and
    abs(left_height - right_height) <= 1
)
返回(
self.isBalanced(root.left)和
self.isBalanced(root.right)和

abs(左高度-右高度)您调用
self.isBalanced(root.left)
self.isBalanced(root.right)
,但从未对其返回值做任何处理。@Aran Fey-hmmm,我明白了。这可能会导致问题。但是根据打印的结果,它是否会进入if状态(因为差值大于1)?
self.isBalanced(root.left)
self.isBalanced(root.right)
if abs(left_height - right_height) > 1:
    return False
return (
    self.isBalanced(root.left) and
    self.isBalanced(root.right) and
    abs(left_height - right_height) <= 1
)