Practical-4 (Expression Tree)
Practical-4 (Expression Tree)
}node;
class stack
{
stacknode *top;
public:
stack()
{
top=NULL;
}
node* topp()
{
return (top->data);
}
int isempty()
{
if(top==NULL)
return 1;
return 0;
}
void push(node* a)
{
stacknode *p;
p=new stacknode();
p->data=a;
p->next=top;
top=p;
}
node* pop()
{ stacknode *p;
node* x;
x=top->data;
p=top;
top=top->next;
return x;
}
};
int main()
{
node *r=NULL,*r1;
char postfix[10],prefix[10];
int x;
int ch,choice;
do
{
cout<<"\n\t****TREE OPERATIONS****\n1.Construct tree from postfix expression/
prefix expression\n2.Inorder traversal\n3.Preorder traversal\n4.Postorder
traversal\n5.Exit\nEnter your choice=";
cin>>ch;
switch(ch)
{
case 1:cout<<"ENTER CHOICE:\n1.Postfix expression\n2.Prefix expression\
nchoice=";
cin>>choice;
if(choice==1)
{
cout<<"\nEnter postfix expression=";
cin>>postfix;
r=create_post(postfix);
}
else
{
cout<<"\nEnter prefix expression=";
cin>>prefix;
r=create_pre(prefix);
}
cout<<"\n\nTree created successfully";
break;
case 2:cout<<"\nInorder Traversal of tree:\n";
inorder(r);
cout<<"\n Without recursion:\t";
inorder_non_recursive(r);
break;
case 3:cout<<"\nPreorder Traversal of tree:\n";
preorder(r);
cout<<"\npreorder traversal without recursion:\t";
preorder_non_recursive(r);
break;
case 4:cout<<"\nPostorder Traversal of tree:\n";
postorder(r);
cout<<"\npostorder traversal without recursion";
postorder_non_recursion(r);
break;
}
}while(ch!=5);
return 0;
}
stack s;
while(t!=NULL)
{
s.push(t);
t=t->left;
}
while(s.isempty()!=1)
{
t=s.pop();
cout<<t->data;
t=t->right;
while(t!=NULL)
{
s.push(t);
t=t->left;
}
}
void preorder_non_recursive(node *t)
{
stack s;
while(t!=NULL)
{
cout<<t->data;
s.push(t);
t=t->left;
}
while(s.isempty()!=1)
{
t=s.pop();
t=t->right;
while(t!=NULL)
{
cout<<t->data;
s.push(t);
t=t->left;
}
}
}
}
else
cout<<t->data;
}
}