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;
    }
};
相关推荐
dying_man11 分钟前
LeetCode--42.接雨水
算法·leetcode
笑鸿的学习笔记17 分钟前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
hardStudy_h31 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
ZZZS05161 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人1 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
位东风1 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
前端拿破轮3 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
雷羿 LexChien4 小时前
C++内存泄漏排查
开发语言·c++
嘉小华4 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
Feliz Da Vida4 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习