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

    你可能感兴趣的文章
    numpy 数组与矩阵的乘法理解
    查看>>
    NumPy 数组拼接方法-ChatGPT4o作答
    查看>>
    numpy 用法
    查看>>
    Numpy 科学计算库详解
    查看>>
    Numpy.fft.fft和numpy.fft.fftfreq有什么不同
    查看>>
    numpy.linalg.norm(求范数)
    查看>>
    Numpy.ndarray对象不可调用
    查看>>
    Numpy.VisibleDeproationWarning:从不整齐的嵌套序列创建ndarray
    查看>>
    Numpy:按多个条件过滤行?
    查看>>
    Numpy:条件总和
    查看>>
    numpy、cv2等操作图片基本操作
    查看>>
    numpy中的argsort的用法
    查看>>
    NumPy中的精度:比较数字时的问题
    查看>>
    numpy判断对应位置是否相等,all、any的使用
    查看>>
    Numpy多项式.Polynomial.fit()给出的系数与多项式.Polyfit()不同
    查看>>
    Numpy如何使用np.umprod重写range函数中i的python
    查看>>
    numpy学习笔记3-array切片
    查看>>
    numpy数组替换其中的值(如1替换为255)
    查看>>
    numpy数组索引-ChatGPT4o作答
    查看>>
    numpy最大值和最大值索引
    查看>>