力扣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--;

    }
}
相关推荐
鑫—萍1 小时前
C++——入门基础(2)
java·开发语言·jvm·数据结构·c++·算法
一只鱼^_2 小时前
力扣第447场周赛
数据结构·算法·leetcode·职场和发展·贪心算法·动态规划·迭代加深
Dante7982 小时前
【多源01BFS】Codeforce:Three States
c++·算法·bfs
步行cgn2 小时前
Java Properties 遍历方法详解
java·开发语言·算法·面试·intellij-idea
学习和思考2 小时前
瑞芯微芯片算法开发初步实践
arm开发·人工智能·嵌入式硬件·深度学习·神经网络·算法
九章云极AladdinEdu4 小时前
存算一体架构下的新型AI加速范式:从Samsung HBM-PIM看近内存计算趋势
人工智能·pytorch·算法·架构·gpu算力·智能电视
legend_jz5 小时前
算法--模拟题目
数据结构·c++·算法
搏博5 小时前
结构模式识别理论与方法
人工智能·深度学习·学习·算法·机器学习
qinyuzhang15 小时前
深入理解C语言中的整形提升与算术转换
数据结构·c++·算法
安全系统学习5 小时前
网络安全之浅析Java反序列化题目
运维·开发语言·网络·算法·安全·web安全·php