【发布时间】:2015-08-14 17:58:00
【问题描述】:
我看到这段代码来自 https://leetcode.com/discuss/37282/simple-python-recursive-solution-bfs-o-n-80ms
这就是
的答案给定一棵二叉树,求其最小深度。
最小深度是沿最短路径的节点数 根
节点向下到最近的叶节点。
class Solution:
# @param {TreeNode} root
# @return {integer}
def minDepth(self, root):
if not root:
return 0
nodes = [(root, 1)]
while nodes:
node, curDepth = nodes.pop(0)
if node.left is None and node.right is None:
return curDepth
if node.left:
nodes.append((node.left, curDepth + 1))
if node.right:
nodes.append((node.right, curDepth + 1))
所以我的困惑是,如果节点 1 有节点 2 和节点 3 作为其 .left 和 .right 子节点,那么堆栈将是 [(node 2, someDepth), (node 3 someDepth)]。然后由于堆栈只会弹出列表的最后一个元素,因此 (node 3 someDepth) 将被解包,而节点 2 将被完全忽略。那么如果节点 2 没有子节点,而节点 3 有子节点,那么使用节点 3 进行后续迭代是不是错了?
【问题讨论】: