python - 判断二叉树是否平衡
问题描述
基本上,此代码用于确定二叉树是否高度平衡。这是我的代码。
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
对于下图中的二叉树二叉树打印的结果是
1 3 3
2 2 0
4 1 1
7 0 0
8 0 0
3 2 2
5 1 1
9 0 0
10 0 0
6 1 1
11 0 0
12 0 0
对于节点 2,left_height
为 2 且right_height
为 0,差值大于 1,应返回False
。但是这段代码返回了True
,我很困惑。
解决方案
您的代码仅检查树顶部的高度是否正确。您需要考虑子树的结果。
这个
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
)
推荐阅读
- sql - 从 Postgres 的另一个表中更新具有最高值的列?
- javascript - 如何定义请求的body参数是否为FormData
- apache-kafka - 如何在 Kafka 的消费者级别维护订单?
- function - 将我的函数应用于 Numpy 数组中的每个位置
- python - fastText 产生零向量
- python - 使用枕头和python3.8调整img大小时出错
- c - 在 C 中重新排列复合初始值设定项的宏
- testing - 对于 Shiro 测试中的类型,方法 expect(boolean) 未定义
- javascript - JS 中以 1 秒延迟返回定义数据的函数
- android - recyclerview 中的 admob 插页式广告实施不起作用?