Skip to content

Commit 2d00cdc

Browse files
authored
Create Sum Root to Leaf Numbers
1 parent 82ab12f commit 2d00cdc

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: Sum Root to Leaf Numbers

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
14+
int ans=0;
15+
void print_sum(vector<int> res, int len)
16+
{
17+
reverse(res.begin(), res.end());
18+
int sum=0;
19+
for(int i=0;i<len;i++)
20+
// cout<<res[i]<<" ";
21+
{
22+
sum = sum + res[i]*pow(10,i);
23+
}
24+
ans += sum;
25+
// cout<<"\n";
26+
}
27+
28+
void sum_paths(TreeNode* root, vector<int> path, int len)
29+
{
30+
if(root==NULL)
31+
return;
32+
33+
path.push_back(root->val);
34+
len++;
35+
36+
if(root->left==NULL and root->right==NULL)
37+
print_sum(path, len);
38+
39+
else
40+
{
41+
sum_paths(root->left, path, len);
42+
sum_paths(root->right, path, len);
43+
}
44+
45+
}
46+
47+
48+
public:
49+
int sumNumbers(TreeNode* root)
50+
{
51+
vector<int> path;
52+
sum_paths(root, path,0);
53+
return ans;
54+
}
55+
};

0 commit comments

Comments
 (0)