【问题标题】:How does this code work to find the Minimum Depth of Binary Tree?这段代码如何找到二叉树的最小深度?
【发布时间】: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 进行后续迭代是不是错了?

【问题讨论】:

    标签: python algorithm tree


    【解决方案1】:

    你缺少的一点是

    nodes.pop(0)
    

    弹出第 0 个元素。

    所以你错了:

    那么由于栈只会弹出列表的最后一个元素,那么...

    想象一棵二叉树:

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

    这里的状态空间将改变为(为简单起见,节点被命名为它们的内容编号):

    # 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.
    

    可以看出,节点的处理宽度(树的)是明智的,所以它是一个 BFS。

    【讨论】:

    • 谢谢。它向我阐明了 BFS 的概念。
    【解决方案2】:

    递归解决方案更容易理解。

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

    【讨论】:

    • OP 发布的有问题的代码比这个递归代码高效得多。此代码遍历整个树。
    猜你喜欢
    • 2014-08-07
    • 2021-07-30
    • 1970-01-01
    • 2016-01-24
    • 2012-10-12
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多