12_二叉树的最小深度

简介: 12_二叉树的最小深度

二叉树的最小深度

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

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

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

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

【思路】当遍历后得到的节点的左、右孩子结点都为空的时候,则说明遍历的最低点了。直接返回当前的的deepth,如果其中一个孩子为空则不是最低点。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)  return 0;
        int depth = 1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            while (levelSize > 0) {
                TreeNode poll = queue.poll();
                levelSize--;
                if (poll.left == null && poll.right == null) {
                    return depth;
                }
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
相关文章
12_二叉树的最小深度
12_二叉树的最小深度
|
5月前
|
C++
二叉树的最小深度(C++)
二叉树的最小深度(C++)
30 1
|
5月前
|
C++ Python
leetcode-111:二叉树的最小深度
leetcode-111:二叉树的最小深度
40 0
|
12月前
【Leetcode -111.二叉树的最小深度 -112.路径总和】
【Leetcode -111.二叉树的最小深度 -112.路径总和】
40 0
|
12月前
|
算法 前端开发
前端算法-二叉树的最小深度
前端算法-二叉树的最小深度
|
存储 算法
算法训练Day17|● 104.二叉树的最大深度 559.n叉树的最大深度● 111.二叉树的最小深度● 222.完全二叉树的节点个数
算法训练Day17|● 104.二叉树的最大深度 559.n叉树的最大深度● 111.二叉树的最小深度● 222.完全二叉树的节点个数
Leetcode 111 二叉树最小深度
Leetcode 111 二叉树最小深度
122 0
力扣 111 104二叉树的最大深度和最小深度总结
力扣 111 104二叉树的最大深度和最小深度总结
48 0
leetcode 111 二叉树最小深度
leetcode 111 二叉树最小深度
59 0
leetcode 111 二叉树最小深度