Skip to content

Commit d0729d3

Browse files
Added day26 solution
1 parent 3aec0df commit d0729d3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Definition for a binary tree node.
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 util(TreeNode *root, int &csum, int &gsum){
13+
if(!root) return;
14+
csum = csum * 10 + root->val;
15+
if(root->left == NULL && root->right == NULL)
16+
gsum += csum;
17+
util(root->left, csum, gsum);
18+
util(root->right, csum, gsum);
19+
csum /= 10; //once we reach one of the bottom of tree, then we start going up from root->left to root to root->right;
20+
}
21+
22+
int util_try(TreeNode *root, int val){
23+
if(!root) return 0;
24+
val = val * 10 + root->val;
25+
if(!root->left && !root->right)
26+
return val;
27+
return util_try(root->left, val) + util_try(root->right, val);
28+
}
29+
30+
int util_try_iter(TreeNode *root){
31+
if(!root) return 0;
32+
33+
queue<TreeNode*> nodeQ;
34+
queue<int> sumQ;
35+
nodeQ.push(root);
36+
sumQ.push(root->val);
37+
int gsum = 0;
38+
39+
while(!nodeQ.empty()){
40+
TreeNode *curr = nodeQ.front();
41+
nodeQ.pop();
42+
43+
int csum = sumQ.front();
44+
sumQ.pop();
45+
46+
if(!curr->left && !curr->right) //basecase
47+
gsum += csum;
48+
49+
if(curr->left){
50+
nodeQ.push(curr->left); //ok..
51+
sumQ.push((csum * 10) + curr->left->val); //not so ok..
52+
}
53+
54+
if(curr->left){
55+
nodeQ.push(curr->right); //ok..
56+
sumQ.push((csum * 10) + curr->right->val); //not so ok..
57+
}
58+
}
59+
return gsum;
60+
}
61+
62+
int sumNumbers(TreeNode* root) {
63+
if(root == NULL) return 0;
64+
int csum = 0, gsum = 0;
65+
return util_try(root,csum);
66+
}
67+
};

0 commit comments

Comments
 (0)