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

递归展开图:


相关推荐
不想编程小谭4 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
01_5 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
_Itachi__7 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉7 小时前
力扣-贪心-376 摆动序列
算法·leetcode
01_8 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW088 小时前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场8 小时前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展
qy发大财8 小时前
分发糖果(力扣135)
数据结构·算法·leetcode
小王努力学编程11 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
夏末秋也凉14 小时前
力扣-贪心-53 最大子数组和
数据结构·算法·leetcode