-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumofallbranchesoftree.cpp
More file actions
65 lines (54 loc) · 1.25 KB
/
Sumofallbranchesoftree.cpp
File metadata and controls
65 lines (54 loc) · 1.25 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
class BinaryTree
{
public:
int value;
BinaryTree*left;
BinaryTree*right;
BinaryTree(int value){
this->value = value;
left = nullptr;
right = nullptr;
}
};
void calculateSum(BinaryTree*root,int sum,vector<int>&ans)
{
if(root==NULL)
{
return;
}
if(root->left == NULL && root->right == NULL)
{
sum+=root->value;
ans.push_back(sum);
return;
}
calculateSum(root->left,sum+root->value,ans);
calculateSum(root->right,sum+root->value,ans);
}
void inorder(BinaryTree*root)
{
BinaryTree*temp = root;
cout<<root->value;
inorder(root->left);
inorder(root->right);
}
int main() {
BinaryTree*root = new BinaryTree(1);
root->left = new BinaryTree(2);
root->right = new BinaryTree(3);
root->left->left = new BinaryTree(4);
root->left->right = new BinaryTree(5);
root->right->left = new BinaryTree(6);
root->right->right = new BinaryTree(7);
root->left->left->left = new BinaryTree(8);
root->left->left->right = new BinaryTree(9);
int sum = 0;
vector<int>ans;
calculateSum(root,sum,ans);
for(int i:ans)
{
cout<<i<<" ";
}
}