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

递归展开图:


相关推荐
黑听人5 小时前
【力扣 困难 C】329. 矩阵中的最长递增路径
c语言·leetcode
YuTaoShao7 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
এ᭄画画的北北9 小时前
力扣-31.下一个排列
算法·leetcode
Swift社区11 小时前
Swift 解 LeetCode 321:拼接两个数组中的最大数,贪心 + 合并全解析
开发语言·leetcode·swift
无聊的小坏坏12 小时前
力扣 239 题:滑动窗口最大值的两种高效解法
c++·算法·leetcode
YuTaoShao12 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao13 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
Zedthm14 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
YuTaoShao14 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man15 小时前
LeetCode--42.接雨水
算法·leetcode