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);
    }
};

递归展开图:


相关推荐
s153352 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔2 小时前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七2 小时前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
JiaJZhong15 小时前
力扣.最长回文子串(c++)
java·c++·leetcode
凌肖战16 小时前
力扣网编程150题:加油站(贪心解法)
算法·leetcode·职场和发展
吃着火锅x唱着歌16 小时前
LeetCode 3306.元音辅音字符串计数2
算法·leetcode·c#
kngines16 小时前
【力扣(LeetCode)】数据挖掘面试题0003: 356. 直线镜像
leetcode·数据挖掘·直线镜像·对称轴
不見星空16 小时前
【leetcode】1751. 最多可以参加的会议数目 II
算法·leetcode
不見星空17 小时前
leetcode 每日一题 3439. 重新安排会议得到最多空余时间 I
算法·leetcode
SsummerC17 小时前
【leetcode100】下一个排列
python·算法·leetcode