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

    你可能感兴趣的文章
    Pandas、Matplotlib、Pyecharts数据分析实践
    查看>>
    Pandas中文官档 ~ 基础用法1
    查看>>
    Pandas中文官档~基础用法2
    查看>>
    Pandas中文官档~基础用法5
    查看>>
    Pandas中文官档~基础用法6
    查看>>
    Pandas中的GROUP BY AND SUM不丢失列
    查看>>
    Pandas之iloc、loc
    查看>>
    pandas交换两列
    查看>>
    pandas介绍-ChatGPT4o作答
    查看>>
    pandas去除Nan值
    查看>>
    pandas实战:电商平台用户分析
    查看>>
    Pandas库函数
    查看>>
    Pandas库常用方法、函数集合
    查看>>
    pandas打乱数据的顺序
    查看>>
    pandas指定列数据归一化
    查看>>
    pandas改变一列值(通过apply)
    查看>>
    Pandas数据分析的环境准备
    查看>>
    Pandas数据可视化怎么做?用实战案例告诉你!
    查看>>
    Pandas数据处理与分析教程:从基础到实战
    查看>>
    Pandas数据结构之DataFrame常见操作
    查看>>