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

递归展开图:


相关推荐
洛水水6 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
过期动态8 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒8 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
洛水水8 小时前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅8 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-8 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
洛水水9 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂9 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode
菜菜的顾清寒12 小时前
力扣HOT100(34)图论-岛屿数量
算法·leetcode·图论
圣保罗的大教堂12 小时前
leetcode 2657. 找到两个数组的前缀公共数组 中等
leetcode