111. Minimum Depth of Binary Tree

problem

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.

求根到叶的最短路径长度

solution

  • 应该用BFS
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root:
            queue = [[root]]
            i = 1
            while True:
                element = []
                for item in queue.pop():
                    if item.left is None and item.right is None:
                        return i
                    if item.left:
                        element.append(item.left)
                    if item.right:
                        element.append(item.right)
                i += 1
                queue.append(element[:])
        return 0

discuss

DFS的递归解法

def minDepth(self, root):
    if not root: return 0
    d = map(self.minDepth, (root.left, root.right))
    return 1 + (min(d) or max(d))
def minDepth(self, root):
    if not root: return 0
    d, D = sorted(map(self.minDepth, (root.left, root.right)))
    return 1 + (d or D)
posted @ 2016-11-21 10:42  Salmd  阅读(104)  评论(0)    收藏  举报