代码随想录之二叉树的最小深度

文章介绍了如何使用Java解决力扣第111题,主要提供了两种方法:递归和迭代。递归法中,当左右子节点有一个为空时结束递归;迭代法则利用队列,遇到叶子节点时返回深度。

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

本题在力扣111
本题思路学习于代码随想录

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 {
    public int minDepth(TreeNode root) {
        if (root ==null){
            return 0;
        }
        int leftlength = minDepth(root.left);
        int rightlength = minDepth(root.right);
        //因为是找最小值,所以左右孩子只要有一个为空就返回值
        if (root.left == null) {
            return rightlength + 1;
        }
        if (root.right == null) {
            return leftlength + 1;
        }
        int min = Math.min(leftlength,rightlength) +1;
        
        return min;
    }
}

方法二 :迭代法,使用队列来模拟存储的过程。
在每次遍历一层的时间,判断这个结点是不是叶子结点,如果是叶子结点的话就return,因为求的是最小长度。

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int depth =0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            depth ++;
            for (int i=0;i<size;i++){
                TreeNode temp = queue.poll();
                if(temp.left == null && temp.right ==null){   // 如果这个结点是叶子结点,所以应该是&&
                    return depth;
                }
                if (temp.left != null) {
                    queue.add(temp.left);
                }
                if(temp.right != null){
                    queue.add(temp.right);
                }
            }
        }
        return depth;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值