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

简介: leetcode-111:二叉树的最小深度

题目

题目链接

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

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

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

示例 1:

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

示例 2:

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

解答

二叉树的最大深度有些类似

最大深度很容易理解,最小深度可有一个误区,如图:

左右子节点都不存在才算

图片来源

python写法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        queue = [root]
        depth = 1  # 根节点自带深度1
        while queue:
            l = len(queue)
            for _ in range(l): 
                cur=  queue.pop(0)
                left,right = cur.left,cur.right
                if not left and not right: 
                    return depth
                if left:
                    queue.append(left)
                if right:
                    queue.append(right)
            depth+=1
        return depth

c++写法

注意这里初始化int depth=1; 而 二叉树的最大深度 初始化depth=0;

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> queue;
        queue.push(root);
        int depth=1;
        while(!queue.empty()){
            int l=queue.size();
            for(int i=0;i<l;i++){
                TreeNode* cur=queue.front();
                queue.pop();
                TreeNode* left=cur->left;
                TreeNode* right=cur->right;
                if(!left&&!right){
                    return depth;
                }
                if(left){
                    queue.push(left);
                }
                if(right){
                    queue.push(right);
                }
            }
            depth++;
        }
        return depth;
    }
};


相关文章
|
21天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
13 0
|
9天前
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
16 0
|
12天前
|
存储 Java
JAVA数据结构刷题 -- 力扣二叉树
JAVA数据结构刷题 -- 力扣二叉树
18 0
|
13天前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
|
13天前
[LeetCode]——965——单值二叉树
[LeetCode]——965——单值二叉树
|
13天前
LeetCode——101——对称二叉树
LeetCode——101——对称二叉树
37 12
|
13天前
|
存储
LeetCode———144—— 二叉树的前序遍历
LeetCode———144—— 二叉树的前序遍历
|
13天前
LeetCode——965. 单值二叉树
LeetCode——965. 单值二叉树
|
15天前
|
算法
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(下)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
8 1
|
15天前
|
算法 C++
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(上)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
7 1