forked from sat5297/hacktober-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinorder.cpp
More file actions
145 lines (125 loc) · 2.54 KB
/
inorder.cpp
File metadata and controls
145 lines (125 loc) · 2.54 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
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
142
143
144
145
// all traversals in recursive and non recursive form
// std i/o - Enter postfix expression: ab*c+d/
// std o/p - inorder - a*b+c/d
#include <iostream>
using namespace std;
class Tree
{
char data;
Tree* left;
Tree* right;
public:
Tree* create(char ele);
Tree *construct(char p[]);
void inorder(Tree* base);
void NRinorder(Tree* base);
};
class Stack
{
public:
Tree *t_obj;
Stack* Stack_link;
int flag;
Stack* push(Tree *, Stack *, int);
Stack* pop(Stack* top);
};
Stack* Stack :: push(Tree *ele, Stack *top, int f)
{
Stack* newnode = new Stack;
newnode->flag= f;
newnode->t_obj = ele;
newnode ->Stack_link = NULL;
if(top == NULL)
{
top = newnode;
}
else
{
newnode->Stack_link = top;
top = newnode;
}
return top;
}
Stack* Stack :: pop(Stack* top)
{
Stack *temp = top;
top = top->Stack_link;
delete temp;
return top;
}
Tree * Tree :: create(char ele)
{
Tree* newnode = new Tree;
newnode -> data = ele;
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}
Tree * Tree :: construct(char p[])
{
Stack *top = NULL;
Tree *temp;
int i=0;
while(p[i] != '\0')
{
if(isalnum(p[i]))
{
temp = create(p[i]);
top = top-> push(temp, top,0);
}
else
{
temp = create(p[i]);
temp->right = top->t_obj;
top = top->pop(top);
temp->left = top->t_obj;
top = top->pop(top);
top = top->push(temp, top,0);
}
i++;
}
temp = top->t_obj;
top = top->pop(top);
return temp;
}
void Tree :: inorder(Tree *base)
{
if(base == NULL)
return;
inorder(base->left);
cout<<base->data;
inorder(base->right);
}
void Tree::NRinorder(Tree *base){
Stack *top=NULL;
Tree *current=base;
while(current!=NULL || top!=NULL){
while(current!=NULL){
top=top->push(current,top,0);
current=current->left;
}
if(current==NULL && top!=NULL){
current=top->t_obj;
top=top->pop(top);
cout<<current->data;
current=current->right;
}
else
break;
}
}
int main()
{
char postfix[20];
Tree obj;
Tree *root = NULL;
int op;
cout<<"Enter postfix expression: ";
cin>>postfix;
root=obj.construct(postfix);
cout<<"\n Recursive inorder traversal: ";
obj.inorder(root);
cout<<"\n Non-recursive inorder traversal: ";
obj.NRinorder(root);
return 0;
}