-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path69_binaryTree_kSumPath.cpp
More file actions
63 lines (58 loc) · 1.2 KB
/
69_binaryTree_kSumPath.cpp
File metadata and controls
63 lines (58 loc) · 1.2 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
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
this->data = d;
this->left = NULL;
this->right = nullptr;
}
};
node *buildTree(node *root)
{
cout << "Enter the data: " << endl;
int data;
cin >> data;
root = new node(data);
if (data == -1)
{
return nullptr;
}
cout << "Enter data to insert at left: " << data << endl;
root->left = buildTree(root->left);
cout << "Enter data to insert at right: " << data << endl;
root->right = buildTree(root->right);
return root;
}
void solve(node* root , int k , vector<int> path , int cnt){
if(root == nullptr)
return;
path.push_back(root->data);
solve(root->left, k, path, cnt);
solve(root->right, k, path, cnt);
int size = path.size();
int sum = 0;
for (int i = size - 1; i >= 0; i--){
sum += path[i];
if(sum == k){
cnt++;
}
}
path.pop_back();
}
int sumK(node* root , int k){
vector<int> path;
int cnt = 0;
solve(root , k ,path, cnt);
return cnt;
}
int main()
{
node *root = nullptr;
root = buildTree(root);
}