博客
关于我
LeetCode 111二叉树的最小深度-简单
阅读量:485 次
发布时间:2019-03-06

本文共 1618 字,大约阅读时间需要 5 分钟。

为了解决从根节点到最近叶子节点的最小深度问题,我们可以使用广度优先搜索(BFS)来遍历二叉树。广度优先搜索能够逐层访问每个节点,并记录每个节点到根节点的深度,从而找到离根节点最近的叶子节点的最小深度。

方法思路

  • 初始化队列:将根节点加入队列,并将其深度初始化为1。
  • 遍历队列:逐层访问每个节点,记录其深度。
  • 检查叶子节点:如果当前节点是叶子节点(左右子节点都为空),则更新最小深度。
  • 扩展队列:对于非叶子节点,将左子节点和右子节点加入队列,并将其深度增加1。
  • 返回结果:遍历结束后,返回最小深度。
  • 这种方法确保我们能够找到离根节点最近的叶子节点,从而得到最小深度。

    解决代码

    import java.util.*;class Solution {    public int minDepth(TreeNode root) {        if (root == null) {            return 0;        }        int minDepth = Integer.MAX_VALUE;        Queue
    queue = new LinkedList<>(); queue.add(new NodePair(root, 1)); while (!queue.isEmpty()) { NodePair currentPair = queue.poll(); TreeNode current = currentPair.node; int currentDepth = currentPair.depth; if (current.left == null && current.right == null) { if (currentDepth < minDepth) { minDepth = currentDepth; } } else { if (current.left != null) { queue.add(new NodePair(current.left, currentDepth + 1)); } if (current.right != null) { queue.add(new NodePair(current.right, currentDepth + 1)); } } } return minDepth; } private static class NodePair { TreeNode node; int depth; NodePair(TreeNode node, int depth) { this.node = node; this.depth = depth; } }}

    代码解释

  • 初始化检查:如果根节点为空,直接返回0。
  • 队列初始化:将根节点及其深度1加入队列。
  • 遍历过程:使用队列逐层遍历每个节点,检查是否为叶子节点,并更新最小深度。
  • 扩展子节点:对于非叶子节点,将左子节点和右子节点加入队列,深度增加1。
  • 返回结果:遍历结束后,返回最小深度。
  • 这种方法确保了在最坏情况下也能高效地找到最小深度,适用于大规模树结构。

    转载地址:http://uvhdz.baihongyu.com/

    你可能感兴趣的文章
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>
    npm,yarn,cnpm 的区别
    查看>>
    NPOI
    查看>>
    NPOI之Excel——合并单元格、设置样式、输入公式
    查看>>
    NPOI初级教程
    查看>>
    NPOI利用多任务模式分批写入多个Excel
    查看>>
    NPOI在Excel中插入图片
    查看>>
    NPOI将某个程序段耗时插入Excel
    查看>>
    NPOI格式设置
    查看>>
    NPOI设置单元格格式
    查看>>
    Npp删除选中行的Macro录制方式
    查看>>
    NR,NF,FNR
    查看>>
    nrf24l01+arduino
    查看>>
    nrf开发笔记一开发软件
    查看>>
    nrm —— 快速切换 NPM 源 (附带测速功能)
    查看>>