LeetCode Minimum Depth of Binary Tree

本文介绍了一种算法,用于查找二叉树的最小深度。通过递归和非递归两种方式实现,递归方法考虑特殊情况,非递归采用BFS遍历直到找到最近的叶子节点。

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

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.

思路分析:这题和Maximum Depth of Binary Tree类似,但是现在要返回最小深度,递归的解法需要加一个特殊的判断,就是如果某个node比如root只有一个孩子,这时不能返回最小深度是0,因为只有在叶子节点处(而不是空处)才能计算深度,所以当左孩子为空,传入右孩子递归调用;当右孩子为空,传入左孩子递归调用。而在Maximum Depth of Binary Tree没有这个问题,因为我们是求最大深度,某个node只有一个孩子,我们会计深度为1而不是0。

递归解法如下,多加了对只有一个孩子的情况的判断:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        if(root.left == null) return minDepth(root.right) + 1;
        if(root.right == null) return minDepth(root.left) + 1;
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}

非递归解法借助队列进行BFS计算深度,当遇到第一个叶子节点返回深度即可,最后加了一个return 0保证返回出口,其实叶子节点必然存在,一定会从while循环里面就返回。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        LinkedList<TreeNode> treeNodeQueue = new LinkedList<TreeNode>();
        int level = 1;
        treeNodeQueue.add(root);
        int curLevelNum = 1;
        int nextLevelNum = 0;
        while(!treeNodeQueue.isEmpty()){
            TreeNode curNode = treeNodeQueue.poll();//find and remove; different from peek
            if(curNode.left == null && curNode.right == null) return level;
            curLevelNum--;
            if(curNode.left != null){
                treeNodeQueue.add(curNode.left);
                nextLevelNum++;
            }
            if(curNode.right != null){
                treeNodeQueue.add(curNode.right);
                nextLevelNum++;
            }
            if(curLevelNum == 0){
                level++;
                curLevelNum = nextLevelNum;
                nextLevelNum = 0;//added a level
            }
        }
        return 0;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值