C++ | Leetcode C++题解之第111题二叉树的最小深度

题目:

题解:

cpp 复制代码
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == nullptr) {
            return 0;
        }

        queue<pair<TreeNode *, int> > que;
        que.emplace(root, 1);
        while (!que.empty()) {
            TreeNode *node = que.front().first;
            int depth = que.front().second;
            que.pop();
            if (node->left == nullptr && node->right == nullptr) {
                return depth;
            }
            if (node->left != nullptr) {
                que.emplace(node->left, depth + 1);
            }
            if (node->right != nullptr) {
                que.emplace(node->right, depth + 1);
            }
        }

        return 0;
    }
};
相关推荐
Irissgwe4 小时前
类与对象(三)
开发语言·c++·类和对象·友元
️是784 小时前
信息奥赛一本通—编程启蒙(3395:练68.3 车牌问题)
数据结构·c++·算法
Liangwei Lin5 小时前
LeetCode 118. 杨辉三角
算法·leetcode·职场和发展
计算机安禾5 小时前
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
java·c++·算法
雪度娃娃5 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
我星期八休息5 小时前
Linux系统编程—基础IO
linux·运维·服务器·c语言·c++·人工智能·算法
故事和你916 小时前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论
paeamecium6 小时前
【PAT甲级真题】- String Subtraction (20)
数据结构·c++·算法·pat考试·pat
YL200404267 小时前
047从前序与中序遍历序列构造二叉树
算法·leetcode
计算机安禾7 小时前
【c++面向对象编程】第25篇:仿函数(函数对象):重载operator()
开发语言·c++·算法