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;
        
    }
};
相关推荐
DeepModel几秒前
【概率分布】指数分布(Exponential Distribution)原理、推导与实战
python·算法·概率论
_饭团5 分钟前
指针核心知识:5篇系统梳理3
c语言·数据结构·算法·leetcode·面试·学习方法·改行学it
2401_874732537 分钟前
C++中的状态模式
开发语言·c++·算法
BB学长7 分钟前
LBM vs FVM:谁才是 CFD 的未来?
人工智能·算法·机器学习
闻缺陷则喜何志丹7 分钟前
【枚举】P6786「SWTR-6」GCDs & LCMs|普及+
c++·算法·洛谷
m0_7166670728 分钟前
实时数据压缩库
开发语言·c++·算法
dapeng287035 分钟前
多协议网络库设计
开发语言·c++·算法
星空露珠42 分钟前
又双叒叕统计被炸死的lua脚本
开发语言·数据结构·算法·游戏·lua
阿Y加油吧1 小时前
力扣打卡——day01
java·算法·leetcode
Suifqwu1 小时前
stm32之移植MbedTLS以及算法实现
stm32·嵌入式硬件·算法