首页 > 解决方案 > 分析 BST 高度平衡

问题描述

我正在查看用于检查 BST 是否高度平衡的代码,并且对理解以下代码有疑问。

def is_balanced(cur_node) :
        if (not cur_node) :
            height = 0
            return True, height

        is_left_balanced, left_height = TreeNode.is_balanced(cur_node.left)
        is_right_balanced, right_height = TreeNode.is_balanced(cur_node.right)

        #To get the height of the current node, we find the maximum of the  
        #left subtree height and the right subtree height and add 1 to it
        height = max(left_height, right_height) + 1

        if (not is_left_balanced or not is_right_balanced):
            return False, height

        #If the difference between height of left subtree and height of
        #right subtree is more than 1, then the tree is unbalanced
        if (abs(left_height - right_height) > 1):
            return False, height

        return True, height 

我想知道,为什么我们需要

height = max(left_height, right_height) + 1

找到最大值究竟对我们有什么帮助?

谢谢

标签: pythonbinary-search-tree

解决方案


推荐阅读