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;
    }
};
相关推荐
xlq223223 小时前
22.多态(上)
开发语言·c++·算法
D_evil__3 小时前
[C++高频精进] 并发编程:线程基础
c++
云里雾里!4 小时前
力扣 209. 长度最小的子数组:滑动窗口解法完整解析
数据结构·算法·leetcode
Mr_WangAndy4 小时前
C++17 新特性_第二章 C++17 语言特性_std::any和string_view
c++·string_view·c++40周年·c++17新特性·c++新特性any
CoderYanger5 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列
java·算法·leetcode·机器学习·深度优先·剪枝·1024程序员节
水天需0106 小时前
C++ 三种指针转换深度解析
c++
言言的底层世界6 小时前
c++中STL容器及算法等
开发语言·c++·经验分享·笔记
Mr_WangAndy6 小时前
C++17 新特性_第一章 C++17 语言特性___has_include,u8字符字面量
c++·c++40周年·c++17新特性·__has_include·u8字面量
liu****6 小时前
八.函数递归
c语言·开发语言·数据结构·c++·算法
Vanranrr7 小时前
C++临时对象与悬空指针:一个导致资源加载失败的隐藏陷阱
服务器·c++·算法