A very simple question, similar to path sum.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 void sum(TreeNode *root, int now, int &res) {13 if (root == NULL) {14 return;15 }16 now = now * 10 + root->val;17 if (root->left == NULL && root->right == NULL) {18 res += now;19 }20 sum(root->left, now, res);21 sum(root->right, now, res);22 }23 int sumNumbers(TreeNode *root) {24 int res = 0;25 sum(root, 0, res);26 return res;27 }28 };
However, after reading the problem solution, I found that the solution is better than my algorithm! Learn now!
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 int sum(TreeNode *root, int now) {13 if (root == NULL) {14 return 0;15 }16 now = now * 10 + root->val;17 if (root->left == NULL && root->right == NULL) {18 return now;19 }20 return sum(root->left, now) + sum(root->right, now);21 }22 int sumNumbers(TreeNode *root) {23 return sum(root, 0);24 }25 };
Fewer parameters, shorter code!