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

递归展开图:


相关推荐
Kuo-Teng8 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
橘颂TA11 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
愚润求学14 小时前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
·白小白16 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
一匹电信狗20 小时前
【C++11】Lambda表达式+新的类功能
服务器·c++·算法·leetcode·小程序·stl·visual studio
在等晚安么20 小时前
力扣面试150题打卡
算法·leetcode·面试
User_芊芊君子1 天前
【LeetCode经典题解】递归破解对称二叉树之谜
算法·leetcode·职场和发展
Rock_yzh1 天前
LeetCode算法刷题——49. 字母异位词分组
数据结构·c++·学习·算法·leetcode·职场和发展·哈希算法
小欣加油1 天前
leetcode 2654 使数组所有元素变成1的最少操作次数
数据结构·c++·算法·leetcode·职场和发展
Kt&Rs1 天前
11.12 LeetCode 题目汇总与解题思路
算法·leetcode