-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1022SumOfRootToLeafBinaryNumbers.cpp
More file actions
48 lines (45 loc) · 1.08 KB
/
1022SumOfRootToLeafBinaryNumbers.cpp
File metadata and controls
48 lines (45 loc) · 1.08 KB
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
/**
* 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) {}
* };
*/
class Solution {
public:
int sum=0;
int convert(string s){
int j=s.length()-1;
int sum=0;
int count=0;
while(j>=0){
if(s[j]=='1'){
sum+=pow(2,count);
}
count++;
j--;
}
return sum;
}
void check(TreeNode* root,string store){
if(root==NULL) return;
store+=(root->val)+48;
if(root->left==NULL&&root->right==NULL){
sum+=convert(store);
return;
}
check(root->left,store);
check(root->right,store);
return;
}
int sumRootToLeaf(TreeNode* root) {
if(root==NULL) return 0;
string store="";
check(root,store);
return sum;
}
};