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.


题意:给一个二叉树,求出根节点到叶子节点(终端结点)的最短路径

解法:使用BFS广度优先遍历,记录层数,遇到左右同时为null,返回层数

# 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(not root):
            return 0
        queue = [root]
        level = 1
        while(queue):
            count = len(queue)
            for i in range(0, count):
                node = queue.pop(0)
                if(not node.left and not node.right):
                    return level
                if(node.left):
                    queue.append(node.left)
                if(node.right):
                    queue.append(node.right)
            level += 1






posted @   xiejunzhao  阅读(133)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示