分析BST高度平衡

时间:2018-05-29 04:27:30

标签: python binary-search-tree

我正在查看用于检查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

找到最大值究竟是如何帮助我们的?

谢谢

0 个答案:

没有答案