Description
Submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
return sumRootToLeafUtil(root, 0);
}
int sumRootToLeafUtil(TreeNode* root, int sum) {
sum = (sum << 1) + root->val;
if(root->left == nullptr && root->right == nullptr) return sum;
int res = 0;
if(root->left) res += sumRootToLeafUtil(root->left, sum);
if(root->right) res += sumRootToLeafUtil(root->right, sum);
return res;
}
};