Skip to content

Commit ddaaa60

Browse files
committed
🎉 passed: recursion tree
1 parent ae82d0b commit ddaaa60

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎1022.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
struct TreeNode {
2+
int val;
3+
TreeNode *left;
4+
TreeNode *right;
5+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
6+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
7+
TreeNode(int x, TreeNode *left, TreeNode *right)
8+
: val(x), left(left), right(right) {}
9+
};
10+
11+
class Solution {
12+
public:
13+
int sumRootToLeaf(TreeNode *root, int base = 0) {
14+
if (!root) return base;
15+
int left =
16+
root->left ? sumRootToLeaf(root->left, (base << 1) + root->val) : 0;
17+
int right =
18+
root->right ? sumRootToLeaf(root->right, (base << 1) + root->val) : 0;
19+
20+
if (!root->left && !root->right) {
21+
return (base << 1) + root->val;
22+
} else {
23+
return left + right;
24+
}
25+
}
26+
};
27+
28+
int main(int argc, char const *argv[]) {
29+
Solution s;
30+
TreeNode *root =
31+
new TreeNode(1, new TreeNode(0, new TreeNode(0), new TreeNode(1)),
32+
new TreeNode(1, new TreeNode(0), new TreeNode(1)));
33+
s.sumRootToLeaf(root);
34+
35+
return 0;
36+
}

0 commit comments

Comments
 (0)