LeetCode111.二叉树的最小深度

力扣题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/

题目叙述:

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

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

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

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

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

思路:

这题仍然能通过层序遍历的模板实现,当我们遍历到某一个节点,发现它的左孩子和右孩子都为空时,我们就找到了最低的节点,此时计算这个节点到根节点路径上的节点数就是最小深度,我们也可以定义depth

量,计算最小深度。

AC代码如下:

class Solution {
public:
int minDepth(TreeNode* root) {
//定义depth变量,表示最小深度
int depth = 0;
if (root == NULL) return 0;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
//遍历一层就让depth加1
depth++;
while (size--) {
TreeNode* cur = que.front();
que.pop();
if (cur->left != NULL) que.push(cur->left);
if (cur->right != NULL) que.push(cur->right);
//当某一个节点左右孩子都为空时证明这个节点它是最低的节点
if (cur->left == NULL && cur->right == NULL) return depth;
}
}
return depth;
}
};
posted @   Tomorrowland_D  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示