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

    }
}
相关推荐
真就死难3 小时前
完全日期(日期枚举问题)--- 数学性质题型
算法·日期枚举
不知道取啥耶3 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
花间流风4 小时前
晏殊几何学讲义
算法·矩阵·几何学·情感分析
@心都4 小时前
机器学习数学基础:42.AMOS 结构方程模型(SEM)分析的系统流程
人工智能·算法·机器学习
我想吃烤肉肉5 小时前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode
北顾南栀倾寒6 小时前
[算法笔记]cin和getline的并用、如何区分两个数据对、C++中std::tuple类
笔记·算法
一只大侠8 小时前
牛客周赛A:84:JAVA
算法
豆豆酱8 小时前
Informer方法论详解
算法
槐月初叁8 小时前
多模态推荐系统指标总结
算法
迪小莫学AI8 小时前
LeetCode 2588: 统计美丽子数组数目
算法·leetcode·职场和发展