20Z218 - Assignment Step 2
20Z218 - Assignment Step 2
ASSIGNMENT
STEP 2
STACK, QUEUE,
BINARY TREE
Name: Harshada R
Class: CSE G1
Roll No: 20Z218
PROBLEM SOLVING
1) GOOGLE
STACK
You're given string ‘STR’ consisting solely of “{“, “}”, “(“, “)”, “[“and “]”.
Determine whether the parentheses are balanced.
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct sNode {
char data;
struct sNode* next;
};
void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
bool areBracketsBalanced(char exp[])
{
int i = 0;
struct sNode* stack = NULL;
while (exp[i])
{
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') {
if (stack == NULL)
return 0;
else if (!isMatchingPair(pop(&stack), exp[i]))
return 0;
}
i++;
}
if (stack == NULL)
return 1;
else
return 0;
}
int main()
{
char exp[100] = "{()}[]";
if (areBracketsBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode* top;
if (*top_ref == NULL) {
printf("Stack overflow n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
BINARY TREE
Given the root node of a binary tree, swap the ‘left’ and ‘right’ children for each
node.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void mirror(struct Node* node)
{
if (node==NULL)
return;
else{
struct Node* temp;
mirror(node->left);
mirror(node->right);
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
void inOrder(struct Node* node)
{
if (node == NULL)
return;
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
int main()
{
struct Node *root = newNode(11);
root->left = newNode(22);
root->right = newNode(33);
root->left->left = newNode(44);
root->left->right = newNode(55);
printf("Inorder traversal of the constructed tree is \n");
inOrder(root);
mirror(root);
printf("\nInorder traversal of the mirror tree is \n");
inOrder(root);
return 0;
}
2) AMAZON
STACK
Given a postfix expression, the task is to evaluate the expression
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
QUEUE
Implement a Queue using an Array
#include <stdio.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void 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 add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
front = 0;
printf("Insert the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
}
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", 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");
}
}
BINARY TREE
Given a Binary Tree, figure out whether it’s a Binary Search Tree.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct node
{
int data;
};
if (node==NULL)
return 1;
return 0;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
int main(){
root->right = newNode(54);
root->left->left = newNode(17);
root->left->right = newNode(38);
if(isBST(root))
printf("Is BST");
else
printf("Not a BST");
getchar();
return 0;
}
3) MICROSOFT
STACK
Given a stack, the task is to sort it such that the top of the stack has the
greatest element.
#include <stdio.h>
#include <stdlib.h>
struct stack {
int data;
struct stack* next;
};
void initStack(struct stack** s)
{
*s = NULL;
}
x = (*s)->data;
temp = *s;
(*s) = (*s)->next;
free(temp);
return x;
}
int top(struct stack* s) {
return (s->data);
}
void sortedInsert(struct stack** s, int x)
{
if (isEmpty(*s) || x > top(*s)) {
push(s, x);
return;
}
int temp = pop(s);
sortedInsert(s, x);
push(s, temp);
}
void sortStack(struct stack** s)
{
if (!isEmpty(*s)) {
int x = pop(s);
sortStack(s);
sortedInsert(s, x);
}
}
void printStack(struct stack* s)
{
while (s) {
printf("%d ", s->data);
s = s->next;
}
printf("\n");
}
int main()
{
struct stack* top;
initStack(&top);
push(&top, 30);
push(&top, -85);
push(&top, 18);
push(&top, 14);
push(&top, -73);
printf("Stack elements before sorting:\n");
printStack(top);
sortStack(&top);
printf("\n\n");
printf("Stack elements after sorting:\n");
printStack(top);
return 0;
}
QUEUE
Implement a Queue Data Structure specifically to store integer data using a Singly
Linked List or an array.
#include <stdio.h>
#include <stdlib.h>
struct QNode {
int key;
struct QNode* next;
};
struct Queue {
struct QNode *front, *rear;
};
struct QNode* newNode(int k)
{
struct QNode* temp = (struct QNode*)malloc(sizeof(struct QNode));
temp->key = k;
temp->next = NULL;
return temp;
}
struct Queue* createQueue()
{
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}
void enQueue(struct Queue* q, int k)
{
struct QNode* temp = newNode(k);
if (q->rear == NULL) {
q->front = q->rear = temp;
return;
}
q->rear->next = temp;
q->rear = temp;
}
void deQueue(struct Queue* q)
{
if (q->front == NULL)
return;
struct QNode* temp = q->front;
q->front = q->front->next;
if (q->front == NULL)
q->rear = NULL;
free(temp);
}
int main()
{
struct Queue* q = createQueue();
enQueue(q, 1);
enQueue(q, 2);
deQueue(q);
deQueue(q);
enQueue(q, 3);
enQueue(q, 4);
enQueue(q, 5);
deQueue(q);
printf("Queue Front : %d \n", q->front->key);
printf("Queue Rear : %d", q->rear->key);
return 0;
}
BINARY TREE
Given two binary trees, the task is to find if both of them are identical or not.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int identicalTrees(struct node* a, struct node* b)
{
if (a==NULL && b==NULL)
return 1;
if (a!=NULL && b!=NULL)
{
return
(
a->data == b->data &&
identicalTrees(a->left, b->left) &&
identicalTrees(a->right, b->right)
);
}
return 0;
}
int main()
{
struct node *root1 = newNode(12);
struct node *root2 = newNode(12);
root1->left = newNode(22);
root1->right = newNode(32);
root1->left->left = newNode(42);
root1->left->right = newNode(52);
root2->left = newNode(22);
root2->right = newNode(32);
root2->left->left = newNode(42);
root2->left->right = newNode(52);
if(identicalTrees(root1, root2))
printf("Both tree are identical.");
else
printf("Trees are not identical.");
getchar();
return 0;
}
4) FLIPKART
STACK
You are given N elements and your task is to Implement a Stack in which you can
get minimum element
#include <stdio.h>
#include <string.h>
#define MAXSIZE 10
struct stack
{
int stk[MAXSIZE];
int top;
};
struct stack s,m;
void push (struct stack *T, int n)
{
struct stack temp;
temp = *T;
printf("\nElement %d\n",n);
int y;
if (temp.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
temp.top = temp.top + 1;
temp.stk[temp.top] = n;
}
printf("Top index %d\n",temp.top);
*T=temp;
return;
}
int pop(struct stack *T){
int y;
struct stack temp;
temp = *T;
if (temp.top == - 1)
{
printf ("Stack is Empty\n");
*T=temp;
return -1;
}
else
{
y=temp.stk[temp.top];
temp.top = temp.top - 1;
*T=temp;
return(y);
}
}
void specialPush(int num){
int y;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else if(s.top == -1)
{
push(&s,num);
push(&m,num);
}
else{
y = pop(&m);
push(&m,y);
if(num>y){
push(&m,y);
push(&s,num);
}
else{
push(&m,num);
push(&s,num);
}
}
}
int getMin(){
int y;
y = pop(&m);
push(&m,y);
return y;
}
void display (struct stack *T)
{
struct stack temp;
temp = *T;
int i;
if (temp.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = temp.top; i >= 0; i--)
{
printf ("%d\n", temp.stk[i]);
}
}
printf ("\n");
*T=temp;
}
int main()
{
s.top = -1;
m.top = -1;
specialPush(10);
specialPush(5);
specialPush(20);
specialPush(30);
printf("\nAfter 10,5,20,30\n");
display(&m);
printf("Min->%d\n",getMin());
printf("After 10,5,20,30,1 \n");
specialPush(1);
display(&m);
printf("Min->%d\n",getMin());
return 0;
}
BINARY TREE
Given a Binary Tree, find the maximum width of it.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
int getWidth(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);
int getMaxWidth(struct node* root)
{
int maxWidth = 0;
int width;
int h = height(root);
int i;
for (i = 1; i <= h; i++) {
width = getWidth(root, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
int getWidth(struct node* root, int level)
{
if (root == NULL)
return 0;
if (level == 1)
return 1;
else if (level > 1)
return getWidth(root->left, level - 1)+getWidth(root->right, level - 1);
}
int height(struct node* node)
{
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight) ? (lHeight + 1): (rHeight + 1);
}
}
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct node* root = newNode(11);
root->left = newNode(12);
root->right = newNode(13);
root->left->left = newNode(14);
root->left->right = newNode(15);
root->right->right = newNode(18);
root->right->right->left = newNode(16);
root->right->right->right = newNode(17);
printf("Maximum width is %d \n", getMaxWidth(root));
getchar();
return 0;
}
5) ORACLE
1. Implement a Queue using 2 stacks s1 and s2.
#include <stdio.h>
#include <stdlib.h>
struct sNode {
int data;
struct sNode* next;
};
void push(struct sNode** top_ref, int new_data);
int pop(struct sNode** top_ref);
struct queue {
struct sNode* stack1;
struct sNode* stack2;
};
void enQueue(struct queue* q, int x)
{
push(&q->stack1, x);
}
int deQueue(struct queue* q)
{
int x;
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("Q is empty");
getchar();
exit(0);
}
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
x = pop(&q->stack1);
push(&q->stack2, x);
}
}
x = pop(&q->stack2);
return x;
}
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow \n");
getchar();
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref)
{
int res;
struct sNode* top;
if (*top_ref == NULL) {
printf("Stack underflow \n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
int main()
{
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
q->stack1 = NULL;
q->stack2 = NULL;
enQueue(q, 1);
enQueue(q, 2);
enQueue(q, 3);
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
return 0;
}
queue = malloc(sizeof(queue_t));
if (queue == NULL)
return NULL;
queue->max = n;
queue->arr = malloc(sizeof(int) * n);
queue->rear = n - 1;
queue->front = n - 1;
return queue;
}
void queue_insert(queue_t * q, int v) {
if (q->count == q->max)
return;
q->rear = (q->rear + 1) % q->max;
q->arr[q->rear] = v;
q->count++;
}
int queue_remove(queue_t * q) {
int retval;
if (q->count == 0)
return QUEUE_EMPTY_MAGIC;
q->front = (q->front + 1) % q->max;
retval = q->arr[q->front];
q->count--;
return retval;
}
int queue_is_empty(queue_t * q) {
return (q->count == 0);
}
void queue_display(queue_t * q) {
int i = (q->front + 1) % q->max, elements = queue_count(q);
while (elements--) {
printf("[%d], ", q->arr[i]);
i = (i >= q->max) ? 0 : (i + 1);
}
}
#define MAX 128
int main() {
queue_t *q;
int x, select;
q = queue_allocate(MAX);
do {
printf("\n[1] Push\n[2] Pop\n[0] Exit");
printf("\nChoice: ");
scanf(" %d", &select);
switch (select) {
case 1:
printf("\nEnter value to Push:");
scanf(" %d", &x);
stack_push(q, x);
printf("Current Queue:");
queue_display(q);
printf("\n\nPushed Value: %d", x);
break;
case 2:
x = stack_pop(q);
queue_display(q);
if (x == QUEUE_EMPTY_MAGIC)
printf("\n\nNo values removed");
else
printf("\n\nPopped Value: %d", x);
break;
case 0:
printf("\nQutting.\n");
return 0;
default:
printf("\nQutting.\n");
return 0;
}
} while (1);
return 0;
}
3. Given a binary tree, connect the nodes that are at same level. You'll be
given an addition nextRight pointer for the same.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
struct node* nextRight;
};
void connectRecur(struct node* p);
void connect(struct node* p)
{
p->nextRight = NULL;
connectRecur(p);
}
void connectRecur(struct node* p)
{
if (!p)
return;
if (p->left)
p->left->nextRight = p->right;
if (p->right)
p->right->nextRight = (p->nextRight) ? p->nextRight->left : NULL;
connectRecur(p->left);
connectRecur(p->right);
}
struct node* newnode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->nextRight = NULL;
return (node);
}
int main()
{
struct node* root = newnode(10);
root->left = newnode(18);
root->right = newnode(12);
root->left->left = newnode(13);
connect(root);
printf("Following are populated nextRight pointers in the tree "
"(-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight ? root->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight ? root->left->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight ? root->right->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight ? root->left->left->nextRight->data : -1);
return 0;
}
GATE QUESTIONS
1) STACK
1. Which of the following is essential for converting an infix expression to the
postfix form efficiently?
A. An operator stack
B. An operand stack
C. An operand stack and an operator stack
D. A parse tree
GATE CS 1997
Answer: A
Explanation:
An operator stack is essential for converting an infix expression to
the postfix or prefix form whereas an operand stack is essential for postfix or
prefix evaluation.
2) QUEUE
1. A queue is implemented using an array such that ENQUEUE and
DEQUEUE operations are performed efficiently. Which one of the
following statements is CORRECT (n refers to the number of items in the
queue)?
A. Both operation can be performed in O(1) time
B. At most one operation can be performed in O(1) time but the worst case
for the other operation will be 𝛺(n)
C. The worst case time complexity for both operations will be 𝛺(n)
D. Worst case time complexity for both operations will be 𝛺(logn)
GATE CS 2016
Answer: A
Explanation:
We can use circular array to implement both in O(1) time.
It will continue till first call executes insert(Q, i) function. Therefore, the
queue will be reversed.
3) BINARY TREE
1. Which of the following is false?
A. A tree with a n nodes has (n-1) edges
B. A labelled rooted binary tree can be uniquely constructed given its
postorder and preorder traversal results.
C. A complete binary tree with n internal nodes has (n+1) leaves.
D. The maximum number of nodes in a binary tree of height h is (2 h+1 – 1)
GATE CS 1998
Answer: B, C
Explanation:
Option (B) is false because “a labeled rooted binary tree can not be
uniquely constructed given using its postorder and preorder traversal
results”. It need inorder and preorder/postorder for uniquely constructed
binary tree.
Option (C) is false because a complete binary tree with n nodes can have
n leaves also.
2. The preorder traversal of a binary search tree is 15, 10, 12, 11, 20, 18, 16,
19. Which one of the following is the postorder traversal of the tree?
A. 20, 19, 18, 16, 15, 12, 11, 10
B. 10, 11, 12 15, 16, 18, 19, 20
C. 11, 12, 10, 16, 19, 18, 20, 15
D. 19, 16, 18, 20, 11, 12, 10, 15
GATE CS 2020
Answer: C
Explanation:
Preorder: 15, 10, 12, 11, 20, 18, 16, 19
root node: 15
Left sub tree: 10, 12, 11
Right sub tree: 20, 18, 16, 19
15
10 20
12 18
11 16 19
3. Consider the rooted tree with the vertex labelled P as the root
The order in which the nodes are visited during an in-order traversal of the
tree is
P
Q R
S T U V
W
The order in which the nodes are visited during an in-order traversal of the
tree is
A. SQPTRWUV
B. SQPTRUWRV
C. SQPTWUVR
D. SQPTRUWV
GATE CS 2014
Answer: A