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

递归展开图:


相关推荐
文丑颜不良啊15 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z16 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊17 小时前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊19 小时前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 天前
算法之双指针系列(一)
算法·leetcode
Pniubi2 天前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi2 天前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2061~2080题目解析
java·leetcode