Leetcode 111 Minimum Depth of Binary Tree

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.

def min_depth(root)
    return 0 if not root
    return min_depth(root.left) + 1 if not root.right
    return min_depth(root.right) + 1 if not root.left
    [min_depth(root.right), min_depth(root.left)].min + 1
end

 方法二:BFS 结束条件是找到一个没有子树的node

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        stack = [root]
        depth = 1
        while True:
            stack_new = []
            for node in stack:
                if not node.left and not node.right:
                    return depth
                if node.right:
                    stack_new.append(node.right)
                if node.left:
                    stack_new.append(node.left)
            stack = stack_new
            depth += 1

 

posted @ 2015-06-14 15:25  lilixu  阅读(149)  评论(0编辑  收藏  举报