Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[leetcode] 129. Sum Root to Leaf Numbers : https://leetcode.com/problems/sum-root-to-leaf-numbers/
/**
* 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 ans = 0;
void setAns(TreeNode* root, int sum){
if(root == NULL) return;
sum += root->val;
if(root->left == NULL && root->right ==NULL)
ans += sum;
sum *= 10;
setAns(root->left, sum);
setAns(root->right, sum);
}
int sumNumbers(TreeNode* root) {
ans = 0;
setAns(root, 0);
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment