Skip to content

Commit 11f27e7

Browse files
committed
Binary tree path
1 parent 578caaa commit 11f27e7

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

Tree/BinaryTreePaths.cpp

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <string>
4+
using namespace std;
5+
6+
// Node class
7+
class Node
8+
{
9+
public:
10+
int data;
11+
Node *left;
12+
Node *right;
13+
14+
Node(int val)
15+
{
16+
data = val;
17+
left = right = NULL;
18+
}
19+
};
20+
21+
static int idx = -1;
22+
Node *buildTree(vector<int> preorder)
23+
{
24+
idx++;
25+
26+
// base case
27+
if (preorder[idx] == -1)
28+
{
29+
return NULL;
30+
}
31+
32+
// create root node
33+
Node *root = new Node(preorder[idx]);
34+
35+
// left sub tree recursion call
36+
root->left = buildTree(preorder);
37+
38+
// right sub tree recursion call
39+
root->right = buildTree(preorder);
40+
41+
return root;
42+
}
43+
44+
void allPaths(Node *root, string path, vector<string> &ans)
45+
{
46+
// if root is not there
47+
if (!root)
48+
return;
49+
50+
// if it is a leaf node
51+
if (root->left == NULL && root->right == NULL)
52+
{
53+
ans.push_back(path);
54+
return;
55+
}
56+
57+
if (root->left)
58+
{
59+
allPaths(root->left, path + "->" + to_string(root->left->data), ans);
60+
}
61+
62+
if (root->right)
63+
{
64+
allPaths(root->right, path + "->" + to_string(root->right->data), ans);
65+
}
66+
}
67+
68+
vector<string> binaryTreePaths(Node *root)
69+
{
70+
vector<string> ans;
71+
string path = to_string(root->data);
72+
73+
allPaths(root, path, ans);
74+
return ans;
75+
}
76+
77+
int main()
78+
{
79+
vector<int> preorder = {1, 2, -1, -1, 3, 4, -1, -1, -1};
80+
Node *root = buildTree(preorder);
81+
82+
vector<string> paths = binaryTreePaths(root);
83+
84+
cout << "Root-to-leaf paths:\n";
85+
for (const string &p : paths)
86+
{
87+
cout << p << endl;
88+
}
89+
90+
return 0;
91+
}

Tree/BinaryTreePaths.exe

141 KB
Binary file not shown.

0 commit comments

Comments
 (0)