leetcode 1022.从根到叶的二进制数之和

⭐️ 题目描述

leetcode 1022.从根到叶的二进制数之和_第1张图片
leetcode 1022.从根到叶的二进制数之和_第2张图片


leetcode链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/description/

代码:

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

递归展开图:

leetcode 1022.从根到叶的二进制数之和_第3张图片


你可能感兴趣的:(刷题,leetcode,刷题,二叉树)