-
Notifications
You must be signed in to change notification settings - Fork 1
/
129_sum_root_to_leaf_node.cpp
63 lines (59 loc) · 1.59 KB
/
129_sum_root_to_leaf_node.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
int help(TreeNode*root,int ans)
{
if(root==NULL)
return 0;
int temp1=0;
int temp2=0;
if(root->left==NULL && root->right==NULL)
{
return (ans*10 + root->val);
}
if(root->left!=NULL)
{
temp2=ans*10+root->val;
cout<<temp2<<endl;
temp2=help(root->left,temp2);
}
if(root->right!=NULL)
{
temp1=ans*10 + root->val;
temp1=help(root->right,temp1);
cout<<temp1<<endl;
}
return temp1+temp2;
}
public:
int sumNumbers(TreeNode* root) {
if(root==NULL)
return 0;
int ans1=root->val;
int ans2=root->val;
ans1=help(root->left,ans1);
ans2=help(root->right,ans2);
if(ans1==0 && ans2==0)
ans1=root->val;
return (ans1+ans2);
}
};