我正在查看用于检查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
找到最大值究竟是如何帮助我们的?
谢谢