前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:111. Minimum Depth of Binary Tree

LeetCode笔记:111. Minimum Depth of Binary Tree

作者头像
Cloudox
发布2021-11-23 14:17:24
1070
发布2021-11-23 14:17:24
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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.

大意:

给出一个二叉树,找到他最小的深度。 最小的深度是指从根节点到叶子节点距离最短的节点数。

思路:

这道题要找到最短的深度,个人认为更应该用广度优先遍历来做,一层一层地扫过去,哪一层有叶子节点了,就不扫了,把深度返回来。如果用深度优先遍历,每一条路都要走完,要所有路径都走到最后才能确定最短的。

广度优先取一个队列来记录每一层的节点数,利用队列先进先出的特性,一层层扫,每次扫到下一层的都加到队尾,把当前层的个数扫完后就将层数加一,直到找到叶子节点就直接返回当前找的深度。

代码(Java):

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root == null) return 0;
        
        int result = 1;
        queue.offer(root);
        while (!queue.isEmpty()) {
            int levelNum = queue.size();
            for (int i = 0; i < levelNum; i++) {
                if (queue.peek().left == null && queue.peek().right == null) return result;
                
                if (queue.peek().left != null) queue.offer(queue.peek().left);
                if (queue.peek().right != null) queue.offer(queue.peek().right);
                queue.poll();
            }
            result++;
        }
        return result;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档