【算法学习】二叉树的最小深度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:树的遍历,只要能在遍历过程中记住叶子节点和叶子节点处于的层级(到root有几个节点即可)
思路2:树的层序遍历,层序遍历过程中遇到叶子节点即可得到结果

三、参考代码
思路1
public int run(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Map<TreeNode, Integer> map = new HashMap<>();//用于存储非叶子节点到跟的长度
        Map<TreeNode, Integer> map2 = new HashMap<>();//用于存储叶子节点到跟的长度
        Stack<TreeNode> l3 = new Stack<>();//用于存储遍历中的树节点
        l3.push(root);
        map.put(root, 0);
        while (l3.size() > 0) {
            TreeNode tempRoot = l3.pop();
            TreeNode left = tempRoot.left;
            TreeNode right = tempRoot.right;
            if (left != null) {
                l3.push(left);
                map.put(left, map.get(tempRoot) + 1);
            }
            if (right != null) {
                l3.push(right);
                map.put(right, map.get(tempRoot) + 1);
            }
            if (left == null && right == null) {
                map2.put(tempRoot, map.get(tempRoot) + 1);
            }
        }
        int min = Integer.MAX_VALUE;
        Set<TreeNode> set = map2.keySet();
        for (TreeNode item : set) {
            if (map2.get(item) < min) {
                min = map2.get(item);
            }
        }
        return min;
    }
思路2
public int run(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int layer = 1;//用于记录当前层有多少个节点
        Queue<TreeNode> queue = new LinkedTransferQueue<>();//用于存储遍历中的树节点
        TreeNode layerRightNode = root;
        queue.add(root);
        while (queue.size() > 0) {
            TreeNode tempRoot = queue.remove();
            TreeNode left = tempRoot.left;
            TreeNode right = tempRoot.right;
            if (left != null) {
                queue.add(left);
            }
            if (right != null) {
                queue.add(right);
            }
            if (left == null && right == null) {
                return layer;
            }
            if (layerRightNode == tempRoot) {
                layerRightNode = right == null ? left : right;
                layer++;
            }
        }
        return layer;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼠晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值