Ds Assignment 6
Ds Assignment 6
Code:
# include <stdio.h>
# include <string.h>
#include <stdlib.h>
#define MAX_SIZE 50
struct node{
int data;
struct node* left;
struct node* right;
};
struct stack{
int size;
int top;
struct node* *array;
};
}
int isFull(struct stack* stack){
return stack->top-1==stack->size;
}
int isEmpty(struct stack* stack){
return stack->top==-1;
}
void push(struct stack* stack,struct node* node){
if(isFull(stack)) return; //return if stack is full
//increment top of stack and push the node
stack->array[++stack->top]=node;
}
struct node* pop(struct stack* stack){
if(isEmpty(stack)) return NULL; //return if stack is empty
return stack->array[stack->top--]; //return popped element
}
}
void inorder(struct node *root){
struct node *current=root;
struct stack* stack=createStack(MAX_SIZE);
int flag=0;
//run till current is null and stack is empty
while(!flag){
if(current!=NULL){
push(stack,current);
current=current->left; //make left subtree as new root
}
else{
if(!isEmpty(stack)){
current=pop(stack);
printf("%d\t",current->data);
current=current->right;
}
else
flag=1;
}
}
}
struct node* peek(struct stack* stack) {
if (isEmpty(stack))
return NULL;
return stack->array[stack->top];
}
void postorder(struct node *root){
if (root == NULL)
return;
}
int main(){
struct node* root;
root =createTree();
printf("Trees");
int ch;
int node;
int w=1;
printf("Enter you choice: \n1. Preorder\n2.Inorder\n3.Postorder\n4.Exit\n");
while(w==1){
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\nPreorder");
printf("\nPreorder Traversal is: \n");
preorder(root);
printf("\n");
break;
case 2:
printf("\nInorder");
printf("\nInorder Traversal is: \n");
inorder(root);
printf("\n");
break;
case 3:
printf("\nPostorder");
printf("\nPostorder Traversal is: \n");
postorder(root);
printf("\n");
break;
}
}
Output: