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

递归展开图:


相关推荐
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
带多刺的玫瑰14 小时前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
wabs66617 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
不会就选b17 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木18 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
Tisfy18 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历
木井巳19 小时前
【BFS/DFS 解决 FloodFill 算法】衣橱整理
java·算法·leetcode·深度优先·广度优先·宽度优先
shehuiyuelaiyuehao20 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode