[InterviewBit] Sum Root to Leaf Numbers

Sum Root to Leaf Numbers

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
const int mod = 1003;
void helper(TreeNode* A, int& res, long long now) {
if(!A) return;
now = (now * 10 + A->val) % mod;
if(!A->left and !A->right) res = (res + now) % mod;
else {
helper(A->left,res,now);
helper(A->right,res,now);
}
}
int Solution::sumNumbers(TreeNode* A) {
int res = 0;
helper(A,res,0);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/04/PS/interviewbit/sum-root-to-leaf-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.