zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    接口
    多态
    static的用法
    Person类中多个构造方法和测试
    曹操外卖实现功能
    曹操外卖数据表设计
    java中 try catch finally和return联合使用时,代码执行顺序的小细节
    GenerationType四中类型
    spring boot
    VMware修改为静态ip
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/9695610.html
Copyright © 2011-2022 走看看