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;
        
    }
};
相关推荐
信奥卷王15 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵15 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG16 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z17 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛17 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记17 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序18 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室18 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
圣保罗的大教堂18 小时前
leetcode 301. 删除无效的括号 困难
leetcode