leetcode 1022.从根到叶的二进制数之和

⭐️ 题目描述



🌟 leetcode链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/description/

代码:

cpp 复制代码
class Solution {
public:
    int sum (TreeNode* root , int num = 0) {
        if (root == nullptr) {
            return 0;
        }
        int cur = num + root->val;
        if (root->left == nullptr && root->right == nullptr) {
            return cur;
        }
        
        return sum(root->left , cur << 1) + sum(root->right , cur << 1);
    }

    int sumRootToLeaf(TreeNode* root) {
        
        return sum(root);
    }
};

递归展开图:


相关推荐
Navigator_Z2 小时前
LeetCode //C - 1223. Dice Roll Simulation
c语言·算法·leetcode
Tisfy2 小时前
LeetCode 2058.找出临界点之间的最小和最大距离:遍历+遇到极值则更新(这种题谁空间复杂度不是O(1)啊)
linux·数据库·leetcode·链表·题解·模拟·遍历
小欣加油2 小时前
Leetcode2058 找出临界点之间的最小和最大距离
数据结构·c++·算法·leetcode·职场和发展
CoderYanger3 小时前
A.每日一题:3345. 最小可整除数位乘积 I
java·数据结构·程序人生·算法·leetcode·面试·学习方法
玖玥拾4 小时前
LeetCode 1 两数之和
算法·leetcode·职场和发展
旖旎夜光4 小时前
LeetCode 974:和可被 K 整除的子数组(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
alphaTao1 天前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
CoderYanger2 天前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
Navigator_Z2 天前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
2601_949950632 天前
没有现成习题,试试AI再写出题
人工智能·小程序·刷题·练习·小程序推荐