LeetCode 1022. Sum of Root To Leaf Binary Numbers

🔗 https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers

题目

  • 给一个只有 0 和 1 的二叉树
  • 从 root 到 leaf 的 path 组成一个二进制数
  • 返回这棵树的所有路径和

思路

  • dfs 遍历,记录 path 的二进制数
  • 匿名函数减少参数的传递,代码很好写!

代码

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumRootToLeaf(TreeNode* root) {
        int sum = 0;

        auto dfs = [&](this auto&& self, TreeNode* node, int presum) -> void{
            if (node->right == nullptr && node->left == nullptr) {
                sum = sum + presum * 2 + node->val;
                return;
            }
            if (node->right) self(node->right, presum * 2 + node->val);
            if (node->left) self(node->left, presum * 2 + node->val);
        };
        dfs(root, 0);
        return sum;
        
    }
};
相关推荐
OYpBNTQXi1 小时前
SEAL全同态加密CKKS方案入门详解
算法·机器学习·同态加密
蚂蚁数据AntData2 小时前
破解AI“机器味“困境:HeartBench评测实践详解
大数据·人工智能·算法·机器学习·语言模型·开源
ZC跨境爬虫2 小时前
Python异步IO详解:原理、应用场景与实战指南(高并发爬虫首选)
爬虫·python·算法·自动化
倦王2 小时前
力扣日刷47-补
python·算法·leetcode
沉鱼.443 小时前
第十三届题目
c语言·c++·算法
ZHOU_WUYI3 小时前
ppo算法简单实现
人工智能·pytorch·算法
无限进步_3 小时前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
小超超爱学习99373 小时前
大数乘法,超级简单模板
开发语言·c++·算法
Ricardo-Yang4 小时前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
凌波粒4 小时前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展