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

    }
}
相关推荐
chao_78933 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen1 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest1 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder1 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶1 小时前
链表算法之【合并两个有序链表】
java·算法·链表
不吃洋葱.2 小时前
前缀和|差分
数据结构·算法
是白可可呀4 小时前
LeetCode 169. 多数元素
leetcode
jz_ddk4 小时前
[实战]调频(FM)和调幅(AM)信号生成(完整C语言实现)
c语言·算法·信号处理
CloudAce云一5 小时前
谷歌云代理商:谷歌云TPU/GPU如何加速您的AI模型训练和推理
算法
轻语呢喃5 小时前
每日LeetCode : 杨辉三角
javascript·后端·算法