Leetcode: 二叉树的最小深度

# 二叉树的最小深度

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点
示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度 2.

BFS搜索,遇到left and right 均为NULL时,就达到了叶子节点。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        queue = []
        max_length = 0
        root.val = 1
        queue.append(root)
        while len(queue) != 0:
            root = queue.pop(0)
            length = root.val
            if length > max_length:
                max_length = length
            if root.left == None and root.right ==None:
                return max_length
            if(root):
                if root.left:
                    root.left.val = length + 1
                    queue.append(root.left)
                if root.right:
                    root.right.val = length + 1
                    queue.append(root.right)
        return max_length

猜你喜欢

转载自www.cnblogs.com/xmxj0707/p/9695610.html