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

递归展开图:


相关推荐
田梓燊2 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
6Hzlia9 小时前
【Hot 100 刷题计划】 LeetCode 141. 环形链表 | C++ 哈希表直觉解法
c++·leetcode·链表
山甫aa11 小时前
二叉树遍历----从零开始的数据结构
数据结构·c++·二叉树
北顾笙98011 小时前
day35-数据结构力扣
数据结构·算法·leetcode
ulias21213 小时前
leetcode热题 - 4
算法·leetcode·职场和发展
圣保罗的大教堂13 小时前
leetcode 1559. 二维网格图中探测环 中等
leetcode
_日拱一卒14 小时前
LeetCode:148排序链表
算法·leetcode·链表
生信研究猿14 小时前
leetcode 78.子集
算法·leetcode·深度优先
浅念-14 小时前
分治算法专题|LeetCode高频经典题目详细题解
数据结构·c++·算法·leetcode·职场和发展·排序·分治
shehuiyuelaiyuehao15 小时前
算法11,滑动窗口,最大连续1的个数|||
算法·leetcode·职场和发展