Skip to content

Commit f8a3305

Browse files
committed
Adding k_sum_paths
1 parent b1bab4f commit f8a3305

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

tree_problems/k_sum_paths.cpp

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
* Given a binary tree, print all the paths whose sum is equal to k
3+
* 1
4+
* / \
5+
* 3 -1
6+
* / \ / \
7+
* 2 1 4 5
8+
* / / \ \
9+
* 1 1 2 6
10+
*
11+
* For k = 5:
12+
* 3 2
13+
* 3 1 1
14+
* 1 3 1
15+
* 4 1
16+
* 1 -1 4 1
17+
* -1 4 2
18+
* 5
19+
* 1 -1 5
20+
*/
21+
22+
#include <iostream>
23+
#include <vector>
24+
25+
struct TreeNode
26+
{
27+
int data;
28+
TreeNode* left;
29+
TreeNode* right;
30+
TreeNode(int d) : data {d}, left {nullptr}, right {nullptr} { }
31+
};
32+
33+
void printPath(const std::vector<int>& path, int index)
34+
{
35+
for (auto it = path.begin() + index; it != path.end(); ++it)
36+
{
37+
std::cout << *it << " ";
38+
}
39+
std::cout << std::endl;
40+
}
41+
42+
void printKPaths(TreeNode * node, std::vector<int>& paths, int k)
43+
{
44+
if (!node)
45+
{
46+
return;
47+
}
48+
49+
// push the current node to paths
50+
//
51+
paths.push_back(node->data);
52+
53+
// now, lets explore the left and right sub-trees
54+
//
55+
printKPaths(node->left, paths, k);
56+
printKPaths(node->right, paths, k);
57+
58+
// check if we have reached sum of tree nodes to k.
59+
// also, do not break, once we have reached k, as we may have negative
60+
// values too.
61+
//
62+
/*
63+
int sum = 0;
64+
for (int j=paths.size()-1; j>=0; j--)
65+
{
66+
sum += (paths[j]);
67+
if (sum == k)
68+
{
69+
printPath(paths, j);
70+
}
71+
}
72+
*/
73+
int sum = 0;
74+
for (auto it = paths.rbegin(); it != paths.rend(); ++it)
75+
{
76+
sum += (*it);
77+
if (sum == k)
78+
{
79+
int indexFromStart = paths.size() - 1 - (it - paths.rbegin());
80+
printPath(paths, indexFromStart);
81+
}
82+
}
83+
84+
paths.pop_back();
85+
}
86+
87+
int main()
88+
{
89+
TreeNode* root = new TreeNode(1);
90+
root->left = new TreeNode(3);
91+
root->left->left = new TreeNode(2);
92+
root->left->right = new TreeNode(1);
93+
root->left->right->left = new TreeNode(1);
94+
root->right = new TreeNode(-1);
95+
root->right->left = new TreeNode(4);
96+
root->right->left->left = new TreeNode(1);
97+
root->right->left->right = new TreeNode(2);
98+
root->right->right = new TreeNode(5);
99+
root->right->right->right = new TreeNode(2);
100+
101+
int k = 5;
102+
std::vector<int> paths;
103+
printKPaths(root, paths, k);
104+
return 0;
105+
}

0 commit comments

Comments
 (0)