关于检查树是否平衡的函数的疑问?
我在《Coding Interview Cracked》一书中看到,要检查 BST 是否平衡,只需找出最大和最小高度之间的差异,但我不确定它是否 100% 正确。虽然我无法找到反测试用例。
任何人都可以确认这种方法是否正确。
用于检查树是否平衡。
|MaxHieght(root) - MinHieght(root)| <=1
return true
else return false
I read in a book named "Coding Interview Cracked", that to check whether a BST is balanced or not, just find out the difference between the maximum and minimum height but I not sure whether it is 100% correct. Though I am unable to find a counter test case.
Can anyone confirm whether this approach is correct or not.
For checking whether a tree is balanced or not.
|MaxHieght(root) - MinHieght(root)| <=1
return true
else return false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
给出平衡的定义(来自 Pedias Wiki)
这似乎是正确的。由于 minHeight 和 maxHeight 将等于任一侧的高度,因此看起来定义成立
Given the definition of balanced (from the Wiki of Pedias)
This seems correct. Since the minHeight and maxHeight are going to be equal to the height of either side, looks like the definition holds
如果您愿意,也可以尝试这种方式。
华泰
You can try this way also, if you feel like.
HTH