二叉树的最小深度

使用递归实现

public int minDepth(TreeNode node) {
    if (node == null) {
    return 0;
    }
    int d1 = minDepth(node.left); // 1
    int d2 = minDepth(node.right); // 0
    if (d2 == 0) { // 当右子树为null
        return d1 + 1; // 返回左子树深度+1
    }
    if (d1 == 0) { // 当左子树为null
        return d2 + 1; // 返回右子树深度+1
    }
    return Integer.min(d1, d2) + 1;
}

 

跟求最大深度不同,层序遍历最小深度效率更高,因为遇到的第一个叶子节点所在层就是最小深度。

public int minDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int depth = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        depth ++;
        for (int i = 0; i < size; i++) {
            TreeNode poll = queue.poll();
            if (poll.left == null && poll.right == null) {
                return depth;
            }
            if (poll.left != null) {
                queue.offer(poll.left);
            }
            if (poll.right != null) {
                queue.offer(poll.right);
            }
        }
    }
    return depth;
}

 

 

参考

111. 二叉树的最小深度 – 力扣(LeetCode)

黑马数据结构

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇