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

递归展开图:


相关推荐
小丁爱养花32 分钟前
记忆化搜索专题——算法简介&力扣实战应用
java·开发语言·算法·leetcode·深度优先
楠枬3 小时前
双指针算法
java·算法·leetcode
sjsjs113 小时前
【数据结构-差分】力扣1589. 所有排列中的最大和
数据结构·算法·leetcode
孙小二写代码4 小时前
[leetcode刷题]面试经典150题之4删除有序数组中的重复项II(中等)
算法·leetcode·面试
西柚与蓝莓5 小时前
922. 按奇偶排序数组 II 双指针 力扣
数据结构·算法·leetcode
Amor风信子5 小时前
【力扣】2376. 统计特殊整数
算法·leetcode·职场和发展
杰九14 小时前
【算法题】46. 全排列-力扣(LeetCode)
算法·leetcode·深度优先·剪枝
manba_14 小时前
leetcode-560. 和为 K 的子数组
数据结构·算法·leetcode
liuyang-neu14 小时前
力扣 11.盛最多水的容器
算法·leetcode·职场和发展
忍界英雄14 小时前
LeetCode:2398. 预算内的最多机器人数目 双指针+单调队列,时间复杂度O(n)
算法·leetcode·机器人