如何计算二叉树的最小深度

时间:2015-04-07 04:02:55

标签: python algorithm tree

以下是来自leetcode的问题: 给定二叉树,找到它的最小深度。 最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。 如果我理解正确,这意味着我有一棵树

                                                8
                                               / \
                                              3   10
                                             /
                                            1

最小深度应为2(从节点8到10)。 但是,从这两个链接与python代码: http://codesays.com/2014/solution-to-minimum-depth-of-binary-tree-by-leetcode/ https://gist.github.com/Ray1988/9374678 我编译的结果是3 !!!这让我很困惑.....

1 个答案:

答案 0 :(得分:0)

深度优先或深度优先搜索可以找到离根最近的叶子。 BFS可以比搜索整个树任意快(尽管DFS是必需的),尽管它通常会使用更多的内存。

这里是两个实现的完整示例,两个实现都返回树的最小深度,以及在该最小深度处的叶节点。 Depth-first比广度优先更容易实现,因为使用递归很容易表示深度优先算法。

import collections
import heapq

Node = collections.namedtuple('Node', ['v', 'children'])

def min_depth_bfs(root):
    todo = [(1, root)]
    while todo:
        depth, node = heapq.heappop(todo)
        if not node.children: return depth, node
        for c in node.children:
            heapq.heappush(todo, (depth + 1, c))

def min_depth_dfs(node):
    if not node.children: return 1, node
    d, n = min(min_depth_dfs(c) for c in node.children)
    return 1 + d, n

example = Node(8, [Node(3, [Node(1, [])]), Node(10, [])])

print min_depth_dfs(example)
print min_depth_bfs(example)