leetCode——minimum-depth-of-binary-tree(二叉树的最小深度)

博客围绕二叉树最小深度展开,最小深度指从根节点到最近叶子节点的最短路径上的节点数。介绍了深度优先遍历(递归)和广度优先遍历两种方法,指出广度优先遍历类似层序遍历,找到叶子节点即停止,效率比深度优先遍历高。

摘要生成于 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.

  1. 深度优先遍历(递归)

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null)
            return 0;
        if(root.right == null && root.left == null)
            return 1;
        int leftLen = Integer.MAX_VALUE;
        int rightLen = Integer.MAX_VALUE;
        
        if(root.left != null)
           leftLen = run(root.left)+1;
        if(root.right != null)
            rightLen = run(root.right)+1;
        
        return leftLen < rightLen ? leftLen : rightLen;
    }
    

}

2. 广度优先遍历

与二叉树的层序遍历类似。

一旦找到一个叶子节点,那么这个节点肯定是离根节点最短的叶子节点。这个方法因为不用遍历整棵树所以它的效率要比深度优先遍历方法高。

/**
        利用层序遍历(广度优先)找出第一个叶子节点,此为离根节点最短路径的节点。
    **/
    public int run(TreeNode root){
        if(root == null)
            return 0;
        if(root.right == null && root.left == null)
            return 1;

        int count = 0;   //二叉树的层数
        LinkedList<TreeNode> treeNodeQueue = new LinkedList<>();
        if(treeNodeQueue.offer(root)) {
            while (!treeNodeQueue.isEmpty()) {
                count++;
                //遍历二叉树的某一层
                int size = treeNodeQueue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = treeNodeQueue.poll();
                    if (treeNode.left == null && treeNode.right == null)
                        return count;  //如果找到叶子节点,直接返回层数
                    if (treeNode.left != null)
                        treeNodeQueue.offer(treeNode.left);
                    if (treeNode.right != null)
                        treeNodeQueue.offer(treeNode.right);
                }

            }
        }
        return count;     
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值