C++ | Leetcode C++题解之第404题左叶子之和

题目:

题解:

cpp 复制代码
class Solution {
public:
    bool isLeafNode(TreeNode* node) {
        return !node->left && !node->right;
    }

    int sumOfLeftLeaves(TreeNode* root) {
        if (!root) {
            return 0;
        }

        queue<TreeNode*> q;
        q.push(root);
        int ans = 0;
        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            if (node->left) {
                if (isLeafNode(node->left)) {
                    ans += node->left->val;
                }
                else {
                    q.push(node->left);
                }
            }
            if (node->right) {
                if (!isLeafNode(node->right)) {
                    q.push(node->right);
                }
            }
        }
        return ans;
    }
};
相关推荐
Navigator_Z34 分钟前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟34 分钟前
力扣100——双指针
算法·leetcode
小小、码农2 小时前
C++11右值引用与移动语义 —— 从拷贝资源到转移资源
开发语言·网络·c++·网络协议
charlie1145141913 小时前
C++ 的新标准容器:flat_map、inplace_vector 与 mdspan
开发语言·c++·开源项目
唠玖馆4 小时前
c++AVL树
开发语言·c++
橘子汽水1684 小时前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode
蒸蒸yyyyzwd4 小时前
CPP 选手秋招学习笔记 day31
c++·求职招聘
linx2955 小时前
单元三 · 那 C 的底层知识怎么办
c语言·开发语言·数据结构·c++·嵌入式硬件
汉克老师6 小时前
GESP 六级明日冲刺:最后一晚只抓两个大方向
c++·gesp·小学生·学c++编程