-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1022.cpp
More file actions
25 lines (23 loc) · 751 Bytes
/
1022.cpp
File metadata and controls
25 lines (23 loc) · 751 Bytes
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
#include <string>
using namespace std;
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 sumRootToLeaf(TreeNode* root) {
traverse(root, "");
return sum;
}
void traverse(TreeNode*root, string set){
if (root->left) traverse(root->left, set+to_string(root->val));
if (root->right) traverse(root->right, set+to_string(root->val));
if (!root->left && !root->right) sum += stoi(set+to_string(root->val), 0, 2);
}
};