Leetcode 129 Solution
This article provides solution to leetcode question 129 (sum-root-to-leaf-numbers)
Access this page by simply typing in "lcs 129" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/sum-root-to-leaf-numbers
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root, int curr) {
if (root == NULL)
return 0;
int sum = 0;
if (root->left == NULL && root->right == NULL)
{
return curr * 10 + root->val;
}
if (root->left)
sum += sumNumbers(root->left, curr * 10 + root->val);
if (root->right)
sum += sumNumbers(root->right, curr * 10 + root->val);
return sum;
}
int sumNumbers(TreeNode* root) {
return sumNumbers(root, 0);
}
};