-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathSum.cpp
49 lines (44 loc) · 966 Bytes
/
pathSum.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
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int val;
node *left, *right;
node(int data){
val = data;
left = right = NULL;
}
};
node *build(){
int d;
cin>>d;
if(d==-1){
return NULL;
}
node *root = new node(d);
root->left = build();
root->right = build();
return root;
}
void pathSum(vector<int> &ans, node *root, int value){
if(!root->left and !root->right){
ans.push_back(value);
return;
}
if(root->left) pathSum(ans, root->left, value+root->left->val);
if(root->right) pathSum(ans, root->right, value+root->right->val);
}
int main() {
node *root = build();
vector<int> ans;
// if root is null
if(!root) {
cout<<0<<endl;
return 0;
}
pathSum(ans, root, root->val);
cout<<"Sum of different paths in given tree : ";
for(int i=0;i<ans.size();i++){
cout<<ans[i]<<" ";
}
}