二元树的最小深度
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, node):
if node is None:
return 0
else :
# Compute the depth of each subtree
lDepth = self.minDepth(node.left)
rDepth = self.minDepth(node.right)
return min(lDepth, rDepth) + 1
但是,此解决方案在某些测试用例上不起作用,例如高度不平衡的二进制树,它将其转变为链接列表(ex [2,none,3,3,none,4,4,无,5,无,6]
不计数
2
/ \
3
/ \
4
/ \
5
/ \
6
最小深度为5(因为没有孩子 'M亏本,为什么该解决方案不能充分解决此用例?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这是因为
min
函数。从2开始,您的代码检查左侧为0,然后检查右检查并递归检查并返回4。代码> 1 。I think its because of the
min
function. Starting from 2, your code checks the left which is 0, then checks right which is recursively checked and returns 4. However, you callmin(0, 4)+1
which gives you an output of1
.您的代码在
none
上停止递归,这不是treenode
,显然,对于此类对象而言,术语“深度”是未定义的。尝试在所谓的“叶子”上停止递归:没有孩子的节点。查看我的解决方案有关此问题:Your code stops recursion on
None
which is not aTreeNode
, obviously, the term "depth" is undefined for such objects. Try to stop your recursion on so-called "leafs": nodes without children. Check out my solution for this problem:@Avinash,感谢您的边缘案例。
问题@kellybundy
@Avinash, thanks for ID'ing the edge case.
And the problem @kellyBundy https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/