-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
BinaryTreeUsingStack.cpp
141 lines (128 loc) · 3.16 KB
/
BinaryTreeUsingStack.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
Stack data structure is used to construct the binary tree.
This is an iterative process for constructing the binary tree .
-->state variable is providing this functionality for making the process iterative rather than using recursion.
3 states are used-
1. state==1 then add left child
2. state==2 then add right child
3. state==3 then pop the node from stack as both left and rigth child are added for this node.
*/
#include <iostream>
using namespace std;
#include <vector>
#include <stack>
class Tree
{
public:
int val;
int state;
Tree *left;
Tree *right;
Tree()
{
val = 0;
state = 0;
left = NULL;
right = NULL;
}
Tree(int x, int s)
{
val = x;
state = s;
left = NULL;
right = NULL;
}
Tree(int val, int state, Tree *left, Tree *right)
{
this->val = val;
this->state = state;
this->left = left;
this->right = right;
}
// Function to display tree (preorder traversal)
void display(Tree *root)
{
if (root == NULL)
return;
cout << root->val << " ";
display(root->left);
display(root->right);
}
};
int main()
{
int n;
cout << "Enter size of the array:";
cin >> n;
cout << "\nEnter the elements :";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "\n";
Tree t;
stack<Tree *> st;
//initially root is at state =1
Tree *root = new Tree(arr[0], 1);
st.push(root);
int i = 1;
while (st.size() > 0)
{
if (st.top()->state == 1)
{
if (arr[i] != -1)
{
Tree *node = new Tree(arr[i], 1);
//state increased as left child added
st.top()->state++;
st.top()->left = node;
st.push(node);
}
//if arr[i]==-1 then NULL is added
else
{
st.top()->left = NULL;
st.top()->state++;
}
}
else if (st.top()->state == 2)
{
if (arr[i] != -1)
{
Tree *node = new Tree(arr[i], 1);
//state increased as right child added
st.top()->state++;
st.top()->right = node;
if (st.top()->state == 3)
st.pop();
st.push(node);
}
else
{
st.top()->right = NULL;
st.top()->state++;
}
}
if (st.top()->state == 3)
{ //node popped from stack as both left and right child added
st.pop();
}
i++;
}
//preorder traversal of tree
t.display(root);
cout << "\n";
}
/* Sample input.
50, 25, 12, -1, -1, 37, 30, -1, -1, -1, 75, 62, -1, 70, -1, -1, 87, -1, -1
50
/ \
25 75
/ \ / \
12 37 62 87
/ \
30 70
Output: (preorder traversal)
50 25 12 37 30 75 62 70 87
*/