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

    }
}
相关推荐
楼田莉子14 分钟前
C++算法题目分享:二叉搜索树相关的习题
数据结构·c++·学习·算法·leetcode·面试
pusue_the_sun1 小时前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
大锦终1 小时前
【算法】模拟专题
c++·算法
Xの哲學2 小时前
Perf使用详解
linux·网络·网络协议·算法·架构
想不明白的过度思考者2 小时前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
小七rrrrr2 小时前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
code小毛孩2 小时前
leetcodehot100 矩阵置零
算法
何妨重温wdys2 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
姜不吃葱2 小时前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100
PineappleCoder2 小时前
大小写 + 标点全搞定!JS 如何精准统计单词频率?
前端·javascript·算法