-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1022.cpp
36 lines (32 loc) · 965 Bytes
/
1022.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
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 sumRootToLeaf(TreeNode *root, int base = 0) {
if (!root) return base;
int left =
root->left ? sumRootToLeaf(root->left, (base << 1) + root->val) : 0;
int right =
root->right ? sumRootToLeaf(root->right, (base << 1) + root->val) : 0;
if (!root->left && !root->right) {
return (base << 1) + root->val;
} else {
return left + right;
}
}
};
int main(int argc, char const *argv[]) {
Solution s;
TreeNode *root =
new TreeNode(1, new TreeNode(0, new TreeNode(0), new TreeNode(1)),
new TreeNode(1, new TreeNode(0), new TreeNode(1)));
s.sumRootToLeaf(root);
return 0;
}