简体   繁体   English

此代码如何工作以找到二叉树的最小深度?

[英]How does this code work to find the Minimum Depth of Binary Tree?

I see this code from https://leetcode.com/discuss/37282/simple-python-recursive-solution-bfs-on-80ms 我从https://leetcode.com/discuss/37282/simple-python-recursive-solution-bfs-on-80ms看到此代码

And it is the answer for 这是答案

Given a binary tree, find its minimum depth. 给定二叉树,找到其最小深度。

The minimum depth is the number of nodes along the shortest path from the root 最小深度是沿距根最短路径的节点数

node down to the nearest leaf node. 节点到最近的叶节点。

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))

So my confusion is, say if node 1 has node 2 and node 3 as its .left and .right children, so the stack would be [(node 2, someDepth), (node 3 someDepth)]. 所以我的困惑是,假设节点1具有节点2和节点3作为其.left和.right子代,那么堆栈将是[(node 2,someDepth),(node 3 someDepth)]。 Then as the stack would only pop out the last element of the list, then (node 3 someDepth) would be unpacked while node 2 is completely ignored. 然后,由于堆栈仅弹出列表的最后一个元素,因此(节点3 someDepth)将被解压缩,而节点2被完全忽略。 So in case that node 2 has no child, while node 3 has, isn't it wrong using node 3 for the subsequent iteration? 因此,在节点2没有子节点而节点3有子节点的情况下,使用节点3进行后续迭代是否不对呢?

The point you are missing is 你所缺少的是

nodes.pop(0)

pops the 0th element. 弹出第0个元素。

So you are wrong here: 因此,您在这里错了:

Then as the stack would only pop out the last element of the list, then... 然后,因为堆栈只会弹出列表的最后一个元素,所以...

Imagine a binary tree: 想象一棵二叉树:

            1
          /    \
        2        3
     /   \     /   \
    4     5   6      7
 /   \      /   \   /
8     9    10   11 12

Here the state space will change as(for simplicity, nodes are named as their content-numbers): 这里的状态空间将更改为(为简单起见,节点被命名为其内容编号):

# Before 1st iteration.
nodes = [(1, 1)]

# 1st iteration.
node, curDepth = 1, 1
nodes = [(2, 2), (3, 2)]

# 2nd iteration.
node, curDepth = 2, 2
nodes = [(3, 2), (4, 3), (5, 3)]

# 3rd iteration.
node, curDepth = 3, 2
nodes = [(4, 3), (5, 3), (6, 3), (7, 3)]

# 4th iteration.
node, curDepth = 4, 3
nodes = [(5, 3), (6, 3), (7, 3), (8, 4), (9, 4)]

# 5th iteration.
node, curDepth = 5, 3
# Here if node.left is None and node.right is None becomes True and curDepth i.e. 3 is returned.

As it can be seen, the nodes are processed breadth(of the tree) wise so it's a BFS. 可以看出,对节点进行了(树的)广度处理,因此它是一个BFS。

The recursive solution is much easier to understand. 递归解决方案更容易理解。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {integer}
    def minDepth(self, root):
        if root is None:
            return 0

        if root.left is None:
            return 1 + self.minDepth(root.right)

        if root.right is None:
            return 1 + self.minDepth(root.left)

        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM