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

    你可能感兴趣的文章
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    object detection错误之no module named nets
    查看>>
    Object of type 'ndarray' is not JSON serializable
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    object references an unsaved transient instance - save the transient instance before flushing
    查看>>
    Object 类的常见方法有哪些?
    查看>>
    Object-c动态特性
    查看>>
    Object.assign用法
    查看>>
    Object.create
    查看>>
    Object.defineProperty详解
    查看>>
    Object.keys()的详解和用法
    查看>>
    objectForKey与valueForKey在NSDictionary中的差异
    查看>>
    Objective - C 小谈:消息机制的原理与使用
    查看>>
    OBJECTIVE C (XCODE) 绘图功能简介(转载)
    查看>>
    Objective-C ---JSON 解析 和 KVC
    查看>>
    Objective-C 编码规范
    查看>>
    Objective-Cfor循环实现Factorial阶乘算法 (附完整源码)
    查看>>
    Objective-C——判断对象等同性
    查看>>
    objective-c中的内存管理
    查看>>
    Objective-C之成魔之路【7-类、对象和方法】
    查看>>