博客
关于我
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/

    你可能感兴趣的文章
    Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). 大数据ssh权限问题 hadoop起不来 hadoopssh错
    查看>>
    PermissionError:Python 中的 [Errno 13]
    查看>>
    PermissionError:[Errno 13] 权限被拒绝:‘/manage.py‘
    查看>>
    Permutation
    查看>>
    perspective意思_2020年12月英语四级词汇讲解丨考点归纳:perspective
    查看>>
    PE启动盘和U启动盘(第三十六课)
    查看>>
    PE文件,节头有感IMAGE_SECTION_HEADER
    查看>>
    PE查找文件偏移地址
    查看>>
    PE知识复习之PE的导入表
    查看>>
    PFX(Parallel Framework) and Traditional Multithreading
    查看>>
    PGOS:今天动手给电脑装青苹果Win7 X64位系统
    查看>>
    pgpool-II3.1 的内存泄漏(一)
    查看>>
    PgSQL · 特性分析 · PG主备流复制机制
    查看>>
    PGSQL主键序列
    查看>>
    PGSQL安装PostGIS扩展模块
    查看>>
    pg数据库中两个字段相除
    查看>>
    PhalApi:[1.23] 请求和响应:GET和POST两者皆可得及超越JSON格式返回
    查看>>
    Phalcon环境搭建与项目开发
    查看>>
    Phantom.js维护者退出,项目的未来成疑
    查看>>
    Pharmaceutical的同学们都看过来,关于补码运算的复习相关内容
    查看>>