forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbranch-sums.cpp
More file actions
35 lines (32 loc) · 834 Bytes
/
branch-sums.cpp
File metadata and controls
35 lines (32 loc) · 834 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
26
27
28
29
30
31
32
33
34
35
using namespace std;
// This is the class of the input root. Do not edit it.
class BinaryTree {
public:
int value;
BinaryTree *left;
BinaryTree *right;
BinaryTree(int value) {
this->value = value;
left = NULL;
right = NULL;
}
};
vector<int> branchSums(BinaryTree *root) {
// Write your code here.
if (!root->left && !root->right) {
return {root->value};
}
vector<int> result;
if (root->left) {
vector<int> leftBranches = branchSums(root->left);
result.insert(result.end(), leftBranches.begin(), leftBranches.end());
}
if (root->right) {
vector<int> rightBranches = branchSums(root->right);
result.insert(result.end(), rightBranches.begin(), rightBranches.end());
}
for (int i = 0; i < result.size(); i++) {
result[i] += root->value;
}
return result;
}