You are on page 1of 33

STACKS

Expression Evaluation

#include <iostream>
#include <string.h>

using namespace std;

// Stack type
struct Stack
{
int top;
unsigned capacity;
int* array;
};

// Stack Operations
struct Stack* createStack( unsigned capacity )
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));

if (!stack) return NULL;

stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));

if (!stack->array) return NULL;

return stack;
}

int isEmpty(struct Stack* stack)


{
return stack->top == -1 ;
}

char peek(struct Stack* stack)


{
return stack->array[stack->top];
}

char pop(struct Stack* stack)


{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}

int evaluatePostfix(char* exp)


{

struct Stack* stack = createStack(strlen(exp));


int i;

if (!stack) return -1;

for (i = 0; exp[i]; ++i)


{

if (isdigit(exp[i]))
push(stack, exp[i] - '0');

else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}

int main()
{
int size;
cin >> size;
char exp[size];
for(int i =0; i<size; i++){
cin >> exp[i];
}
cout << evaluatePostfix(exp);
return 0;
}
Infix To Postfix

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;

int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}

void infixToPostfix(string s)
{

stack<char> st;
string result;

for (int i = 0; i < s.length(); i++) {


char c = s[i];

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')){
result += c;
result += " ";
}

else if (c == '(')
st.push('(');

else if (c == ')') {
while (st.top() != '(') {
result += st.top();
result += " ";
st.pop();
}
st.pop();
}

else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
result += st.top();
result += " ";
st.pop();
}
st.push(c);
}
}

while (!st.empty()) {
result += st.top();
result += " ";
st.pop();
}

cout << result << endl;


}

int main(){

string exp;
cin >> exp;
infixToPostfix(exp);
return 0;
}
C program for array implementation of stack

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// A structure to represent a stack


struct Stack {
int top;
unsigned capacity;
int* array;
};

// function to create a stack of given capacity. It initializes size of


// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}

// Stack is full when top is equal to the last index


int isFull(struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}

// Stack is empty when top is equal to -1


int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}

// Function to add an item to stack. It increases top by 1


void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}

// Function to remove an item from stack. It decreases top by 1


int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}

// Function to return the top from stack without removing it


int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}

// Driver program to test above functions


int main()
{
struct Stack* stack = createStack(100);

push(stack, 10);
push(stack, 20);
push(stack, 30);

printf("%d popped from stack\n", pop(stack));

return 0;
}
Infix to Prefix

i) Using Arrays

#include<stdio.h>
#include<string.h>
#include<limits.h>
#include<stdlib.h>
# define MAX 100
int top = -1;
char stack[MAX];

// checking if stack is full


int isFull() {
return top == MAX - 1;
}

// checking is stack is empty


int isEmpty() {
return top == -1;
}

// Push function here, inserts value in stack and increments stack top by 1
void push(char item) {
if (isFull())
return;
top++;
stack[top] = item;
}

// Function to remove an item from stack. It decreases top by 1


int pop() {
if (isEmpty())
return INT_MIN;

// decrements top and returns what has been popped


return stack[top--];
}

// Function to return the top from stack without removing it


int peek(){
if (isEmpty())
return INT_MIN;
return stack[top];
}

// A utility function to check if the given character is operand


int checkIfOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
// Fucntion to compare precedence
// If we return larger value means higher precedence
int precedence(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

// The driver function for infix to postfix conversion


int getPostfix(char* expression)
{
int i, j;

for (i = 0, j = -1; expression[i]; ++i)


{
// Here we are checking is the character we scanned is operand or not
// and this adding to to output.
if (checkIfOperand(expression[i]))
expression[++j] = expression[i];

// Here, if we scan character ‘(‘, we need push it to the stack.


else if (expression[i] == '(')
push(expression[i]);

// Here, if we scan character is an ‘)’, we need to pop and print from the stack
// do this until an ‘(‘ is encountered in the stack.
else if (expression[i] == ')')
{
while (!isEmpty(stack) && peek(stack) != '(')
expression[++j] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression
else
pop(stack);
}
else // if an opertor
{
while (!isEmpty(stack) && precedence(expression[i]) <= precedence(peek(stack)))
expression[++j] = pop(stack);
push(expression[i]);
}

// Once all inital expression characters are traversed


// adding all left elements from stack to exp
while (!isEmpty(stack))
expression[++j] = pop(stack);

expression[++j] = '\0';

void reverse(char *exp){

int size = strlen(exp);


int j = size, i=0;
char temp[size];

temp[j--]='\0';
while(exp[i]!='\0')
{
temp[j] = exp[i];
j--;
i++;
}
strcpy(exp,temp);
}
void brackets(char* exp){
int i = 0;
while(exp[i]!='\0')
{
if(exp[i]=='(')
exp[i]=')';
else if(exp[i]==')')
exp[i]='(';
i++;
}
}
void InfixtoPrefix(char *exp){

int size = strlen(exp);

// reverse string
reverse(exp);
//change brackets
brackets(exp);
//get postfix
getPostfix(exp);
// reverse string again
reverse(exp);
}

int main()
{
printf("The infix is: ");

char expression[] = "((a/b)+c)-(d+(e*f))";


printf("%s\n",expression);
InfixtoPrefix(expression);

printf("The prefix is: ");


printf("%s\n",expression);

return 0;
}

ii) Using Dynamically created Stack

#include<string.h>
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>
# define MAX 100

// A structure to represent a stack


struct Stack {
int top;
int maxSize;
// we are storing string in integer array, this will not give error
// as values will be stored in ASCII and returned in ASCII thus, returned as string again
int* array;
};

struct Stack* create(int max)


{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->maxSize = max;
stack->top = -1;
stack->array = (int*)malloc(stack->maxSize * sizeof(int));
return stack;
}

// Checking with this function is stack is full or not


// Will return true is stack is full else false
//Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{
if(stack->top == stack->maxSize - 1){
printf("Will not be able to push maxSize reached\n");
}
// Since array starts from 0, and maxSize starts from 1
return stack->top == stack->maxSize - 1;
}

// By definition the Stack is empty when top is equal to -1


// Will return true if top is -1
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}

// Push function here, inserts value in stack and increments stack top by 1
void push(struct Stack* stack, char item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}

// Function to remove an item from stack. It decreases top by 1


int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}

// Function to return the top from stack without removing it


int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}

// A utility function to check if the given character is operand


int checkIfOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

// Fucntion to compare precedence


// If we return larger value means higher precedence
int precedence(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

// The driver function for infix to postfix conversion


int getPostfix(char* expression)
{
int i, j;

// Stack size should be equal to expression size for safety


struct Stack* stack = create(strlen(expression));
if(!stack) // just checking is stack was created or not
return -1 ;

for (i = 0, j = -1; expression[i]; ++i)


{
// Here we are checking is the character we scanned is operand or not
// and this adding to to output.
if (checkIfOperand(expression[i]))
expression[++j] = expression[i];

// Here, if we scan character ‘(‘, we need push it to the stack.


else if (expression[i] == '(')
push(stack, expression[i]);

// Here, if we scan character is an ‘)’, we need to pop and print from the stack
// do this until an ‘(‘ is encountered in the stack.
else if (expression[i] == ')')
{
while (!isEmpty(stack) && peek(stack) != '(')
expression[++j] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression
else
pop(stack);
}
else // if an opertor
{
while (!isEmpty(stack) && precedence(expression[i]) <= precedence(peek(stack)))
expression[++j] = pop(stack);
push(stack, expression[i]);
}
}

// Once all inital expression characters are traversed


// adding all left elements from stack to exp
while (!isEmpty(stack))
expression[++j] = pop(stack);

expression[++j] = '\0';

void reverse(char *exp){

int size = strlen(exp);


int j = size, i=0;
char temp[size];

temp[j--]='\0';
while(exp[i]!='\0')
{
temp[j] = exp[i];
j--;
i++;
}
strcpy(exp,temp);
}
void brackets(char* exp){
int i = 0;
while(exp[i]!='\0')
{
if(exp[i]=='(')
exp[i]=')';
else if(exp[i]==')')
exp[i]='(';
i++;
}
}
void InfixtoPrefix(char *exp){

int size = strlen(exp);

// reverse string
reverse(exp);
//change brackets
brackets(exp);
//get postfix
getPostfix(exp);
// reverse string again
reverse(exp);
}
int main()
{
printf("The infix is: ");

char expression[] = "((a/b)+c)-(d+(e*f))";


printf("%s\n",expression);
InfixtoPrefix(expression);

printf("The prefix is: ");


printf("%s\n",expression);

return 0;
}
Double Stack – 2 Stacks in a single array

#include <stdio.h>
#define SIZE 20
int array[SIZE]; // declaration of array type variable.
int top1 = -1;
int top2 = SIZE;

//Function to push data into stack1


void push1 (int data)
{
// checking the overflow condition
if (top1 < top2 - 1)
{
top1++;
array[top1] = data;
}
else
{
printf ("Stack is full");
}
}
// Function to push data into stack2
void push2 (int data)
{
// checking overflow condition
if (top1 < top2 - 1)
{
top2--;
array[top2] = data;
}
else
{
printf ("Stack is full..\n");
}
}

//Function to pop data from the Stack1


void pop1 ()
{
// Checking the underflow condition
if (top1 >= 0)
{
int popped_element = array[top1];
top1--;

printf ("%d is being popped from Stack 1\n", popped_element);


}
else
{
printf ("Stack is Empty \n");
}
}
// Function to remove the element from the Stack2
void pop2 ()
{
// Checking underflow condition
if (top2 < SIZE)
{
int popped_element = array[top2];
top2--;

printf ("%d is being popped from Stack 1\n", popped_element);


}
else
{
printf ("Stack is Empty!\n");
}
}

//Functions to Print the values of Stack1


void display_stack1 ()
{
int i;
for (i = top1; i >= 0; --i)
{
printf ("%d ", array[i]);
}
printf ("\n");
}
// Function to print the values of Stack2
void display_stack2 ()
{
int i;
for (i = top2; i < SIZE; ++i)
{
printf ("%d ", array[i]);
}
printf ("\n");
}

int main()
{
int ar[SIZE];
int i;
int num_of_ele;

printf ("We can push a total of 20 values\n");

//Number of elements pushed in stack 1 is 10


//Number of elements pushed in stack 2 is 10
// loop to insert the elements into Stack1
for (i = 1; i <= 10; ++i)
{
push1(i);
printf ("Value Pushed in Stack 1 is %d\n", i);
}
// loop to insert the elements into Stack2.
for (i = 11; i <= 20; ++i)
{
push2(i);
printf ("Value Pushed in Stack 2 is %d\n", i);
}

//Print Both Stacks


display_stack1 ();
display_stack2 ();

//Pushing on Stack Full


printf ("Pushing Value in Stack 1 is %d\n", 11);
push1 (11);

//Popping All Elements from Stack 1


num_of_ele = top1 + 1;
while (num_of_ele)
{
pop1 ();
--num_of_ele;
}

// Trying to Pop the element From the Empty Stack


pop1 ();

return 0;
}
QUEUE

Queue in C

#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
int main()
{
int choice;
while (1)
{
printf("1.Insert element to queue n");
printf("2.Delete element from queue n");
printf("3.Display all elements of queue n");
printf("4.Quit n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice n");
}
}
}
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow n");
else
{
if(front== - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow n");
return;
}
else
{
printf("Element deleted from queue is : %dn", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if(front == - 1)
printf("Queue is empty n");
else
{
printf("Queue is : n");
for(i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("n");
}
}
Queue in C++

#include<iostream>

using namespace std;

class Queue {
private:
int front;
int rear;
int arr[5];

public:
Queue() {
front = -1;
rear = -1;
for (int i = 0; i < 5; i++) {
arr[i] = 0;
}
}
bool isEmpty() {
if (front == -1 && rear == -1)
return true;
else
return false;
}
bool isFull() {
if (rear == 4)
return true;
else
return false;
}
void enqueue(int val) {
if (isFull()) {
cout << "Queue full" << endl;
return;
} else if (isEmpty()) {
rear = 0;
front = 0;
arr[rear] = val;
} else {
rear++;
arr[rear] = val;
}

int dequeue() {
int x = 0;
if (isEmpty()) {
cout << "Queue is Empty" << endl;
return x;
} else if (rear == front) {
x = arr[rear];
rear = -1;
front = -1;
return x;
} else {
cout << "front value: " << front << endl;
x = arr[front];
arr[front] = 0;
front++;
return x;
}
}

int count() {
return (rear - front + 1);
}

void display() {
cout << "All values in the Queue are - " << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
}

};

int main() {
Queue q1;
int value, option;

do {
cout << "\n\nWhat operation do you want to perform? Select Option number. Enter 0 to exit."
<< endl;
cout << "1. Enqueue()" << endl;
cout << "2. Dequeue()" << endl;
cout << "3. isEmpty()" << endl;
cout << "4. isFull()" << endl;
cout << "5. count()" << endl;
cout << "6. display()" << endl;
cout << "7. Clear Screen" << endl << endl;

cin >> option;

switch (option) {
case 0:
break;
case 1:
cout << "Enqueue Operation \nEnter an item to Enqueue in the Queue" << endl;
cin >> value;
q1.enqueue(value);
break;
case 2:
cout << "Dequeue Operation \nDequeued Value : " << q1.dequeue() << endl;
break;
case 3:
if (q1.isEmpty())
cout << "Queue is Empty" << endl;
else
cout << "Queue is not Empty" << endl;
break;
case 4:
if (q1.isFull())
cout << "Queue is Full" << endl;
else
cout << "Queue is not Full" << endl;
break;
case 5:
cout << "Count Operation \nCount of items in Queue : " << q1.count() << endl;
break;
case 6:
cout << "Display Function Called - " << endl;
q1.display();
break;
case 7:
system("cls");
break;
default:
cout << "Enter Proper Option number " << endl;
}

} while (option != 0);

return 0;
}
Circular Queue in C++

#include<iostream>

using namespace std;

class CircularQueue {
private:
int front;
int rear;
int arr[5];
int itemCount;

public:
CircularQueue() {
itemCount = 0;
front = -1;
rear = -1;
for (int i = 0; i < 5; i++) {
arr[i] = 0;
}
}
bool isEmpty() {
if (front == -1 && rear == -1)
return true;
else
return false;
}
bool isFull() {
if ((rear + 1) % 5 == front)
return true;
else
return false;
}
void enqueue(int val) {
if (isFull()) {
cout << "Queue full" << endl;
return;
} else if (isEmpty()) {
rear = 0;
front = 0;
arr[rear] = val;

} else {
rear = (rear + 1) % 5;
arr[rear] = val;

}
itemCount++;

}
int dequeue() {
int x = 0;
if (isEmpty()) {
cout << "Queue is Empty" << endl;
return x;
} else if (rear == front) {
x = arr[rear];
rear = -1;
front = -1;
itemCount--;
return x;
} else {
cout << "front value: " << front << endl;
x = arr[front];
arr[front] = 0;
front = (front + 1) % 5;
itemCount--;
return x;
}
}

int count() {
return (itemCount);
}

void display() {
cout << "All values in the Queue are - " << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
}

};

int main() {
CircularQueue q1;
int value, option;

do {
cout << "\n\nWhat operation do you want to perform? Select Option number. Enter 0 to exit."
<< endl;
cout << "1. Enqueue()" << endl;
cout << "2. Dequeue()" << endl;
cout << "3. isEmpty()" << endl;
cout << "4. isFull()" << endl;
cout << "5. count()" << endl;
cout << "6. display()" << endl;
cout << "7. Clear Screen" << endl << endl;

cin >> option;


switch (option) {
case 0:
break;
case 1:
cout << "Enqueue Operation \nEnter an item to Enqueue in the Queue" << endl;
cin >> value;
q1.enqueue(value);
break;
case 2:
cout << "Dequeue Operation \nDequeued Value : " << q1.dequeue() << endl;
break;
case 3:
if (q1.isEmpty())
cout << "Queue is Empty" << endl;
else
cout << "Queue is not Empty" << endl;
break;
case 4:
if (q1.isFull())
cout << "Queue is Full" << endl;
else
cout << "Queue is not Full" << endl;
break;
case 5:
cout << "Count Operation \nCount of items in Queue : " << q1.count() << endl;
break;
case 6:
cout << "Display Function Called - " << endl;
q1.display();
break;
case 7:
system("cls");
break;
default:
cout << "Enter Proper Option number " << endl;
}

} while (option != 0);

return 0;
}
Double Ended Queue (Dequeue) in C

#include <stdio.h>
#define size 5
int deque[size];
int f = -1, r = -1;
// insert_front function will insert the value from the front
void insert_front(int x)
{
if((f==0 && r==size-1) || (f==r+1))
{
printf("Overflow");
}
else if((f==-1) && (r==-1))
{
f=r=0;
deque[f]=x;
}
else if(f==0)
{
f=size-1;
deque[f]=x;
}
else
{
f=f-1;
deque[f]=x;
}
}

// insert_rear function will insert the value from the rear


void insert_rear(int x)
{
if((f==0 && r==size-1) || (f==r+1))
{
printf("Overflow");
}
else if((f==-1) && (r==-1))
{
r=0;
deque[r]=x;
}
else if(r==size-1)
{
r=0;
deque[r]=x;
}
else
{
r++;
deque[r]=x;
}

// display function prints all the value of deque.


void display()
{
int i=f;
printf("\nElements in a deque are: ");

while(i!=r)
{
printf("%d ",deque[i]);
i=(i+1)%size;
}
printf("%d",deque[r]);
}

// getfront function retrieves the first value of the deque.


void getfront()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at front is: %d", deque[f]);
}

// getrear function retrieves the last value of the deque.


void getrear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at rear is %d", deque[r]);
}

// delete_front() function deletes the element from the front


void delete_front()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[f]);
f=-1;
r=-1;

}
else if(f==(size-1))
{
printf("\nThe deleted element is %d", deque[f]);
f=0;
}
else
{
printf("\nThe deleted element is %d", deque[f]);
f=f+1;
}
}

// delete_rear() function deletes the element from the rear


void delete_rear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[r]);
f=-1;
r=-1;

}
else if(r==0)
{
printf("\nThe deleted element is %d", deque[r]);
r=size-1;
}
else
{
printf("\nThe deleted element is %d", deque[r]);
r=r-1;
}
}

int main()
{
insert_front(20);
insert_front(10);
insert_rear(30);
insert_rear(50);
insert_rear(80);
display(); // Calling the display function to retrieve the values of deque
getfront(); // Retrieve the value at front-end
getrear(); // Retrieve the value at rear-end
delete_front();
delete_rear();
display(); // calling display function to retrieve values after deletion
return 0;
}
TREE TRAVERSAL

Inorder = Left Root Right


Preorder = Root Left Right
Postorder = Left Right Root

//Tree Traversal in C

#include <stdio.h>
#include <stdlib.h>

struct node {
int item;
struct node* left;
struct node* right;
};

// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}

// preorderTraversal traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// postorderTraversal traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}

// Create a new Node


struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}

int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);

insertLeft(root->left, 5);
insertRight(root->left, 6);

printf("Inorder traversal \n");


inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);

printf("\nPostorder traversal \n");


postorderTraversal(root);
}
//C Program for Inorder traversal of the binary search tree

#include<stdio.h>
#include<stdlib.h>

struct node
{
int key;
struct node *left;
struct node *right;
};

//return a new node with the given value


struct node *getNode(int val)
{
struct node *newNode;

newNode = malloc(sizeof(struct node));

newNode->key = val;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

//inserts nodes in the binary search tree


struct node *insertNode(struct node *root, int val)
{
if(root == NULL)
return getNode(val);

if(root->key < val)


root->right = insertNode(root->right,val);

if(root->key > val)


root->left = insertNode(root->left,val);

return root;
}

//inorder traversal of the binary search tree


void inorder(struct node *root)
{
if(root == NULL)
return;

//traverse the left subtree


inorder(root->left);

//visit the root


printf("%d ",root->key);

//traverse the right subtree


inorder(root->right);
}

int main()
{
struct node *root = NULL;

int data;
char ch;
/* Do while loop to display various options to select from to decide the input */
do
{
printf("\nSelect one of the operations::");
printf("\n1. To insert a new node in the Binary Tree");
printf("\n2. To display the nodes of the Binary Tree(via Inorder Traversal).\n");

int choice;
scanf("%d",&choice);
switch (choice)
{
case 1 :
printf("\nEnter the value to be inserted\n");
scanf("%d",&data);
root = insertNode(root,data);
break;
case 2 :
printf("\nInorder Traversal of the Binary Tree::\n");
inorder(root);
break;
default :
printf("Wrong Entry\n");
break;
}

printf("\nDo you want to continue (Type y or n)\n");


scanf(" %c",&ch);
} while (ch == 'Y'|| ch == 'y');

return 0;
}

You might also like