• 0111-二叉树的最小深度


    给定一个二叉树,找出其最小深度。

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    说明:叶子节点是指没有子节点的节点。

    示例 1:

    输入:root = [3,9,20,null,null,15,7]
    输出:2
    示例 2:

    输入:root = [2,null,3,null,4,null,5,null,6]
    输出:5

    提示:

    树中节点数的范围在 [0, 105] 内
    -1000 <= Node.val <= 1000

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

    python

    # 0104.二叉树的最大深度
    class Solution:
        def levelOrder(self, root: TreeNode) -> int:
            """
            迭代法:双端队列,每次把单层的节点遍历出队列,另外将对应的左右节点加入队列
            :param root:
            :return:
            """
            if not root:
                return 0
    
            queue = [(root, 1)]
            while queue:
                cur, depth = queue.pop(0)
                # 当左右节点都空时,返回depth
                if cur.left == None and cur.right == None:
                    return depth
                if cur.left: # 添加当前pop节点的左节点进入队列
                    queue.append((cur.left, depth+1))
                if cur.right: # 添加当前pop节点的右节点进入队列
                    queue.append((cur.right, depth+1))
    
            return 0
    

    golang

    package binaryTree
    
    // 迭代遍历
    func minDepth(root *TreeNode) int {
    	if root == nil { // 空时返回
    		return 0
    	}
    	queue := []*TreeNode{}
    	depth := []int{}
    	queue = append(queue, root)
    	depth = append(depth, 1)
    
    	for i:=0;i<len(queue);i++ {
    		node := queue[i]
    		res := depth[i]
    
    		if node.Left == nil && node.Right == nil {
    			return res
    		}
    
    		if node.Left != nil { // 节点的左节点入队
    			queue = append(queue, node.Left)
    			depth = append(depth, res + 1)
    		}
    		if node.Right != nil { // 节点的右节点入队
    			queue = append(queue, node.Right)
    			depth = append(depth, res + 1)
    		}
    
    	}
    	return 0
    }
    
    
  • 相关阅读:
    POJ 1222 高斯消元更稳
    Maven与Eclipse使用中遇到的问题解决之道
    Java并发之任务的描述和执行
    XMemcached简单使用示例
    Java的容器类小结
    Java系统属性与Preferences API的简单介绍
    你知道自己执行的是哪个jre吗?
    Log4J配置文件详解
    Java日志工具之SLF4J
    Java日志工具之Log4J
  • 原文地址:https://www.cnblogs.com/davis12/p/15550293.html
Copyright © 2020-2023  润新知