力扣111二叉树的最小深度(DFS)

Problem: 111. 二叉树的最小深度

文章目录

题目描述

思路

1.欲望求出最短的路径,先可以记录一个变量minDepth,同时记录每次当前节点所在的层数currentDepth

2.在递的过程中,每次递一层,也即使当前又往下走了一层,则currentDepth++,当到达叶子节点时,比较并取出min【minDepth, currentDepth】

3.在归的过程中,因为是在往上层归,则currentDepth--;

4.返回最终的minDepth即可

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);最坏空间复杂度

Code

DFS

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
     // record the minimum depth 
        private int minDepth = Integer.MAX_VALUE;
        // record the depth of the current node being traversed
        private int currentDepth = 0;

    public int minDepth(TreeNode root) {
       if (root == null) {
        return 0;
       }
       // start DFS traverssal from the root node
       travers(root);
       return minDepth;
    }

    private void travers(TreeNode root) {
        if (root == null) {
            return;
        }
    // increase the current depth when entering a node in the preorder position
    currentDepth++;

    // if the current node is a leaf, update the minimum depth
    if (root.left == null && root.right == null) {
        minDepth = Math.min(minDepth, currentDepth);
    }

    travers(root.left);
    travers(root.right);

    // decrease the current depth when leaving a node in the postorder position
    currentDepth--;

    }
}
相关推荐
naruto_lnq几秒前
泛型编程与STL设计思想
开发语言·c++·算法
踩坑记录16 分钟前
leetcode hot100 94. 二叉树的中序遍历 easy 递归 dfs
leetcode
zxsz_com_cn21 分钟前
设备预测性维护算法分类及优劣势分析,选型指南来了
算法·分类·数据挖掘
m0_748708051 小时前
C++中的观察者模式实战
开发语言·c++·算法
然哥依旧1 小时前
【轴承故障诊断】基于融合鱼鹰和柯西变异的麻雀优化算法OCSSA-VMD-CNN-BILSTM轴承诊断研究【西储大学数据】(Matlab代码实现)
算法·支持向量机·matlab·cnn
qq_537562671 小时前
跨语言调用C++接口
开发语言·c++·算法
Tingjct1 小时前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
C雨后彩虹1 小时前
计算疫情扩散时间
java·数据结构·算法·华为·面试
yyy(十一月限定版)2 小时前
寒假集训4——二分排序
算法
星火开发设计2 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识