python - 分析 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
找到最大值究竟对我们有什么帮助?
谢谢
解决方案
推荐阅读
- salesforce - for循环的工作以获得最小值
- excel - VBA日期+逻辑
- elasticsearch - 使用python elasticsearch-dsl的elasticsearch字段名称中的多个下划线
- r - 在ggplot中按中位数排序
- docker - 使用密码生成的 ssh 密钥从 docker 访问私有仓库
- python - python opencv 使用 BFMatcher knn 匹配 HOG 描述符
- java - Spring 服务器没有响应 GET 请求
- javascript - 如何从单个反应组件呈现不同的数据?
- python-3.x - 调查 TensorFlow 中的 Float16 训练
- android - 从 GitHub 克隆项目时出现 Android Studio 3.1.3 错误