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

    }
}
相关推荐
程序喵大人37 分钟前
【C++进阶】STL算法与函数对象 - 04 find、count和any_of把查询写成意图
开发语言·c++·算法
豆沙沙包?38 分钟前
c++中引用(P7-P11)
java·c++·算法
不会代码的小猴1 小时前
标准模板库(STL)
开发语言·c++·笔记·算法
ZhouDevin1 小时前
算法论文/高效微调4——DoRA:权重分解的低秩适配方法
算法
evans在进步2 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先
AI探索先锋2 小时前
A* 路径规划:四种算法的进化史-学习
学习·算法
旖旎夜光2 小时前
LeetCode 202:快乐数(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针
cpp_25013 小时前
P1113 [USACO02FEB] 杂务
数据结构·c++·算法·动态规划·图论·拓扑排序·洛谷题解
月光船幽幽3 小时前
门控函数SHS阈值与调制机制解析
人工智能·python·算法
Doraemomo3 小时前
数据结构-哈希表
数据结构·算法·散列表