leetcode-111-二叉树的最小深度


本题是leetcode,地址:111. 二叉树的最小深度

题目

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7]
3
/
9 20
/
15 7
返回它的最小深度 2.

分析

此题采用BFS的思路解决,不了解请移步:搜索思想——DFS & BFS基础基础篇

BFS 的核心思想就是把一些问题抽象成图,从一个点开 始,向四周开始扩散。一般来说, BFS 算法都是用「队列」这种数据结构,每次将一个节点周围的所有节点加入队列。 BFS 出现的常⻅场景,问题的本质就 是让你在一幅「图」中找到从起点 start 到终点 target 的最近距离,这道题的思路就有了,起点是root,终点就是最靠近根节点的那个「叶子节点」,即if (cur.left == null && cur.right == null) ;根据此,可以写出我们的代码;

code

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

你的鼓励也是我创作的动力

打赏地址

原文地址:https://www.cnblogs.com/yangsanchao/p/13299811.html