[LeetCode] 111. Minimum Depth of Binary Tree

本文探讨了如何使用深度优先搜索和递归方法解决LeetCode上的二叉树最小深度问题,通过具体示例和代码解析,展示了算法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接: https://leetcode.com/problems/minimum-depth-of-binary-tree/

1. 题目介绍

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.
给定一个二叉树,返回它最小的深度。
最小的深度是指从头节点到叶子节点最短的距离。
叶子节点是指没有子节点的节点
Example:
Given binary tree [3,9,20,null,null,15,7],
return its minimum depth = 2.
在这里插入图片描述

2. 解题思路

本题和 104. Maximum Depth of Binary Tree 非常相似。一个是求树的最大深度,一个是求树的最小深度。方法都是一样的,那就是深度优先搜索+递归。

唯一不同之处在于,在求最小深度时,需要考虑只有左子树或者只有右子树的情况。比如测试样例 [1,2] , 1是根节点,2是左子树,没有右子树。这是返回的结果应该2,而不是1.

实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        return helper(0,root);
    }
    public int helper(int depth,TreeNode root){
        if(root == null){
            return depth;
        }
        if(root.left == null && root.right == null){
            return depth + 1;
        }
        
        int l = (root.left  == null ? Integer.MAX_VALUE : helper(depth+1,root.left) );
        int r = (root.right == null ? Integer.MAX_VALUE : helper(depth+1,root.right) );
        
        return Math.min(l, r);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值