-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstructBinaryTreeFRomBracketRepresenation.cpp
125 lines (110 loc) · 2.71 KB
/
constructBinaryTreeFRomBracketRepresenation.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Implemented by Kritagya Kumra
/* C++ program to construct a binary tree from
the given string */
#include <iostream>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/* A binary tree node has data, pointer to left
child and a pointer to right child */
struct Node
{
int data;
Node *left, *right;
};
/* Helper function that allocates a new node */
Node *newNode(int data)
{
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* This function is here just to test */
void preOrder(Node *node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// function to return the index of close parenthesis
int findIndex(string str, int si, int ei)
{
if (si > ei)
return -1;
// Inbuilt stack
stack<char> s;
for (int i = si; i <= ei; i++)
{
// if open parenthesis, push it
if (str[i] == '(')
s.push(str[i]);
// if close parenthesis
else if (str[i] == ')')
{
if (s.top() == '(')
{
s.pop();
// if stack is empty, this is
// the required index
if (s.empty())
return i;
}
}
}
// if not found return -1
return -1;
}
// function to construct tree from string
Node *treeFromString(string str, int si, int ei)
{
// Base case
if (si > ei)
return NULL;
cout << endl
<< endl;
cout << "Previous The si is " << si << endl;
cout << "Previous The ei is " << ei << endl;
int num = 0;
// In case the number is having more than 1 digit
while (si <= ei && str[si] >= '0' && str[si] <= '9')
{
num *= 10;
num += (str[si] - '0');
si++;
}
cout << "The answer is " << num << endl;
// new root
Node *root = newNode(num);
int index = -1;
// if next char is '(' find the index of
// its complement ')'
if (si <= ei && str[si] == '(')
{
index = findIndex(str, si, ei);
cout << "The si is " << si << endl;
cout << "The ei is " << ei << endl;
cout << "The index is " << index << endl;
}
// if index found
if (index != -1)
{
// call for left subtree
root->left = treeFromString(str, si + 1, index - 1);
// call for right subtree
root->right = treeFromString(str, index + 2, ei - 1);
}
return root;
}
// Driver Code
int main()
{
string str = "4(2(3)(1))(6(5))";
Node *root = treeFromString(str, 0, str.length() - 1);
preOrder(root);
}
// Implemented by Kritagya Kumra