CONVERSION OF EXPRESSION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Stack structure to store operators and operands
#define MAX 100
char stack[MAX];
int top = -1;
// Function to check if the character is an operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
// Function to check if the character is an operand (either a digit or letter)
int isOperand(char c) {
return isalpha(c) || isdigit(c);
// Function to return precedence of operators
int precedence(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
// Function to check if the operator is left-associative
int isLeftAssociative(char c) {
return !(c == '^');
// Function to push to stack
void push(char c) {
if (top < MAX - 1) {
stack[++top] = c;
// Function to pop from stack
char pop() {
if (top == -1) {
return -1; // Return -1 if stack is empty
return stack[top--];
// Function to peek the top of the stack
char peek() {
if (top == -1) {
return -1;
return stack[top];
// Function to convert infix to postfix
void infixToPostfix(char *infix, char *postfix) {
int i, k = 0;
char symbol;
for (i = 0; infix[i] != '\0'; i++) {
symbol = infix[i];
if (isOperand(symbol)) {
postfix[k++] = symbol;
} else if (symbol == '(') {
push(symbol);
} else if (symbol == ')') {
while (top != -1 && peek() != '(') {
postfix[k++] = pop();
pop(); // Pop '(' from stack
} else if (isOperator(symbol)) {
while (top != -1 && precedence(peek()) >= precedence(symbol) && isLeftAssociative(symbol))
{
postfix[k++] = pop();
push(symbol);
while (top != -1) {
postfix[k++] = pop();
postfix[k] = '\0'; // Null-terminate the postfix expression
// Function to reverse a string (used in prefix conversion)
void reverse(char *str) {
int i, j;
char temp;
int len = strlen(str);
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
// Function to convert infix to prefix
void infixToPrefix(char *infix, char *prefix) {
// Reverse the infix expression
reverse(infix);
// Replace '(' with ')' and vice versa
for (int i = 0; infix[i] != '\0'; i++) {
if (infix[i] == '(') {
infix[i] = ')';
} else if (infix[i] == ')') {
infix[i] = '(';
// Convert the reversed infix to postfix
char postfix[MAX];
infixToPostfix(infix, postfix);
// Reverse the postfix result to get the prefix
reverse(postfix);
strcpy(prefix, postfix);
// Main function to drive the program
int main() {
char infix[MAX], result[MAX];
int choice;
// Input the infix expression
printf("Enter the infix expression: ");
fgets(infix, MAX, stdin);
infix[strcspn(infix, "\n")] = '\0'; // Remove newline character from input
// Ask the user for the choice of conversion
printf("Choose the conversion:\n");
printf("1. Convert to Postfix\n");
printf("2. Convert to Prefix\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
infixToPostfix(infix, result);
printf("Postfix Expression: %s\n", result);
break;
case 2:
infixToPrefix(infix, result);
printf("Prefix Expression: %s\n", result);
break;
default:
printf("Invalid choice!\n");
break;
return 0;
}
PSEUDO CODE FOR CONVERSION OF EXPRESSION
// Function to check if a character is an operator
FUNCTION isOperator(c):
RETURN (c == '+' OR c == '-' OR c == '*' OR c == '/' OR c == '^')
// Function to check if a character is an operand (alphabet or digit)
FUNCTION isOperand(c):
RETURN (c is alphanumeric)
// Function to return precedence of operators
FUNCTION precedence(c):
IF c == '^' THEN RETURN 3
IF c == '*' OR c == '/' THEN RETURN 2
IF c == '+' OR c == '-' THEN RETURN 1
RETURN 0
// Function to check if operator is left associative
FUNCTION isLeftAssociative(c):
RETURN NOT (c == '^')
// Function to push to stack
FUNCTION push(c):
IF stack is not full THEN
Push c onto stack
END IF
// Function to pop from stack
FUNCTION pop():
IF stack is not empty THEN
POP the top element from stack
ELSE
RETURN -1 (indicating empty stack)
// Function to peek the top element of the stack
FUNCTION peek():
IF stack is not empty THEN
RETURN top element of stack
ELSE
RETURN -1 (indicating empty stack)
// Function to convert infix to postfix
FUNCTION infixToPostfix(infix):
INITIALIZE an empty string postfix
FOR each character symbol in infix:
IF symbol is an operand THEN
Append symbol to postfix
ELSE IF symbol is '(' THEN
Push '(' onto stack
ELSE IF symbol is ')' THEN
WHILE stack is not empty AND peek() is not '(':
POP from stack and append to postfix
END WHILE
Pop '(' from stack
ELSE IF symbol is an operator THEN
WHILE stack is not empty AND precedence(peek()) >= precedence(symbol) AND
isLeftAssociative(symbol):
POP from stack and append to postfix
END WHILE
Push symbol onto stack
END FOR
// Pop all remaining operators from stack and append to postfix
WHILE stack is not empty:
POP from stack and append to postfix
RETURN postfix
// Function to reverse a string
FUNCTION reverse(str):
INITIALIZE i = 0, j = length(str) - 1
WHILE i < j:
Swap str[i] and str[j]
INCREMENT i and DECREMENT j
END WHILE
// Function to convert infix to prefix
FUNCTION infixToPrefix(infix):
// Reverse the infix expression
Reverse(infix)
// Replace '(' with ')' and vice versa
FOR each character c in infix:
IF c == '(' THEN
c = ')'
ELSE IF c == ')' THEN
c = '('
END IF
END FOR
// Convert the modified infix to postfix
postfix = infixToPostfix(infix)
// Reverse the postfix result to get the prefix expression
Reverse(postfix)
RETURN prefix
// Main Program
PRINT "Enter the infix expression:"
INPUT infix
PRINT "Choose the conversion:"
PRINT "1. Convert to Postfix"
PRINT "2. Convert to Prefix"
INPUT choice
IF choice == 1 THEN
postfix = infixToPostfix(infix)
PRINT "Postfix Expression: " + postfix
ELSE IF choice == 2 THEN
prefix = infixToPrefix(infix)
PRINT "Prefix Expression: " + prefix
ELSE
PRINT "Invalid choice!"
END IF
END
EVALUATION OF EXPRESSION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define MAX 100
// Stack structure for operands
float operandStack[MAX];
int topOperand = -1;
// Stack structure for operators
char operatorStack[MAX];
int topOperator = -1;
// Function to push an operand to the operand stack
void pushOperand(float value) {
if (topOperand < MAX - 1) {
operandStack[++topOperand] = value;
// Function to pop an operand from the operand stack
float popOperand() {
if (topOperand == -1) {
printf("Stack underflow!\n");
exit(1);
return operandStack[topOperand--];
// Function to push an operator to the operator stack
void pushOperator(char operator) {
if (topOperator < MAX - 1) {
operatorStack[++topOperator] = operator;
}
// Function to pop an operator from the operator stack
char popOperator() {
if (topOperator == -1) {
printf("Operator stack underflow!\n");
exit(1);
return operatorStack[topOperator--];
// Function to check if a character is an operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
// Function to check if a character is a number (operand)
int isOperand(char c) {
return (isdigit(c) || c == '.');
// Function to get the precedence of an operator
int precedence(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
// Function to perform the arithmetic operation
float applyOperator(float operand1, float operand2, char operator) {
switch (operator) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
case '^': return pow(operand1, operand2);
default: return 0;
// Function to convert the infix expression to postfix
void infixToPostfix(char* infix, char* postfix) {
int i, k = 0;
char symbol;
for (i = 0; infix[i] != '\0'; i++) {
symbol = infix[i];
if (isOperand(symbol)) {
postfix[k++] = symbol; // Directly append operands to postfix
} else if (symbol == '(') {
pushOperator(symbol);
} else if (symbol == ')') {
while (topOperator != -1 && operatorStack[topOperator] != '(') {
postfix[k++] = popOperator(); // Pop operators until '(' is found
popOperator(); // Discard the '('
} else if (isOperator(symbol)) {
while (topOperator != -1 && precedence(operatorStack[topOperator]) >=
precedence(symbol)) {
postfix[k++] = popOperator(); // Pop operators of higher or equal precedence
pushOperator(symbol); // Push the current operator to the stack
// Pop all remaining operators in the stack
while (topOperator != -1) {
postfix[k++] = popOperator();
postfix[k] = '\0'; // Null-terminate the postfix expression
// Function to evaluate the postfix expression
float evaluatePostfix(char* postfix) {
for (int i = 0; postfix[i] != '\0'; i++) {
char symbol = postfix[i];
if (isOperand(symbol)) {
// Convert char to float and push it onto the operand stack
pushOperand(symbol - '0');
} else if (isOperator(symbol)) {
float operand2 = popOperand();
float operand1 = popOperand();
float result = applyOperator(operand1, operand2, symbol);
pushOperand(result); // Push the result back onto the operand stack
// The final result will be the only element left in the operand stack
return popOperand();
int main() {
char infix[MAX], postfix[MAX];
float result;
// Input the infix expression
printf("Enter an infix expression (use spaces between operands and operators): ");
fgets(infix, MAX, stdin);
infix[strcspn(infix, "\n")] = '\0'; // Remove newline character from input
// Convert infix expression to postfix
infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
// Evaluate the postfix expression
result = evaluatePostfix(postfix);
printf("Evaluation Result: %.2f\n", result);
return 0;
PSEUDO CODE FOR EVALUATION OF EXPRESSION
FUNCTION isOperator(c):
RETURN (c == '+' OR c == '-' OR c == '*' OR c == '/' OR c == '^')
FUNCTION isOperand(c):
RETURN (c IS DIGIT OR c == '.')
FUNCTION precedence(c):
IF c == '^' THEN
RETURN 3
ELSE IF c == '*' OR c == '/' THEN
RETURN 2
ELSE IF c == '+' OR c == '-' THEN
RETURN 1
ELSE
RETURN 0
FUNCTION applyOperator(operand1, operand2, operator):
IF operator == '+' THEN
RETURN operand1 + operand2
ELSE IF operator == '-' THEN
RETURN operand1 - operand2
ELSE IF operator == '*' THEN
RETURN operand1 * operand2
ELSE IF operator == '/' THEN
RETURN operand1 / operand2
ELSE IF operator == '^' THEN
RETURN operand1 raised to the power operand2
FUNCTION infixToPostfix(infix, postfix):
INITIALIZE empty operator stack
INITIALIZE empty result string postfix
FOR each character c in infix DO:
IF c is an operand THEN:
ADD c to postfix
ELSE IF c == '(' THEN:
PUSH '(' to operator stack
ELSE IF c == ')' THEN:
WHILE operator stack is not empty AND top of stack is not '(':
POP operator from stack and append to postfix
POP '(' from stack
ELSE IF c is an operator THEN:
WHILE operator stack is not empty AND precedence of operator at top of stack >= precedence
of current operator:
POP operator from stack and append to postfix
PUSH current operator to stack
END FOR
WHILE operator stack is not empty:
POP operator from stack and append to postfix
RETURN postfix
FUNCTION evaluatePostfix(postfix):
INITIALIZE empty operand stack
FOR each character c in postfix DO:
IF c is an operand THEN:
CONVERT operand to number and PUSH onto operand stack
ELSE IF c is an operator THEN:
POP operand2 from operand stack
POP operand1 from operand stack
result = applyOperator(operand1, operand2, c)
PUSH result onto operand stack
END FOR
RETURN top of operand stack (the result)
MAIN FUNCTION:
PRINT "Enter an infix expression (use spaces between operands and operators):"
READ infix expression
REMOVE newline from infix expression
CALL infixToPostfix with infix as argument and store result in postfix
PRINT "Postfix Expression: " + postfix
CALL evaluatePostfix with postfix as argument and store result in result
PRINT "Evaluation Result: " + result
IMPLEMENTATION OF QUEUE
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Defining maximum size of the queue
// Queue structure
struct Queue {
int front;
int rear;
int items[MAX];
};
// Function to initialize the queue
void initQueue(struct Queue *q) {
q->front = -1;
q->rear = -1;
// Function to check if the queue is full
int isFull(struct Queue *q) {
if (q->rear == MAX - 1) {
return 1;
return 0;
// Function to check if the queue is empty
int isEmpty(struct Queue *q) {
if (q->front == -1 || q->front > q->rear) {
return 1;
return 0;
// Function to add an element to the queue
void enqueue(struct Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
} else {
if (q->front == -1) { // If the queue is empty
q->front = 0;
q->rear++;
q->items[q->rear] = value;
printf("%d enqueued to the queue\n", value);
// Function to remove an element from the queue
int dequeue(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue\n");
return -1; // Return a sentinel value indicating an error
} else {
int dequeuedValue = q->items[q->front];
q->front++;
if (q->front > q->rear) { // Reset the queue if it becomes empty
q->front = q->rear = -1;
}
return dequeuedValue;
// Function to display the queue
void display(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
} else {
printf("Queue: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
printf("\n");
int main() {
struct Queue q;
initQueue(&q); // Initialize the queue
int choice, value;
while (1) {
// Menu for operations
printf("\nQueue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
// Enqueue operation
printf("Enter a value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
// Dequeue operation
value = dequeue(&q);
if (value != -1) {
printf("%d dequeued from the queue\n", value);
break;
case 3:
// Display the queue
display(&q);
break;
case 4:
// Exit the program
printf("Exiting the program...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
PSEUDO CODE FOR IMPLEMENTATION OF QUEUE
FUNCTION initQueue(Queue):
SET [Link] = -1
SET [Link] = -1
FUNCTION isFull(Queue):
IF [Link] == MAX - 1 THEN
RETURN True
ELSE
RETURN False
FUNCTION isEmpty(Queue):
IF [Link] == -1 OR [Link] > [Link] THEN
RETURN True
ELSE
RETURN False
FUNCTION enqueue(Queue, value):
IF isFull(Queue) THEN
PRINT "Queue is full! Cannot enqueue value."
ELSE:
IF [Link] == -1 THEN
SET [Link] = 0 // Set front to 0 if the queue is empty
END IF
INCREMENT [Link]
SET [Link][[Link]] = value
PRINT "Value enqueued to the queue"
FUNCTION dequeue(Queue):
IF isEmpty(Queue) THEN
PRINT "Queue is empty! Cannot dequeue"
RETURN -1 // Indicating an error (empty queue)
ELSE:
SET dequeuedValue = [Link][[Link]]
INCREMENT [Link]
IF [Link] > [Link] THEN
SET [Link] = -1
SET [Link] = -1 // Reset queue if empty
END IF
RETURN dequeuedValue
FUNCTION display(Queue):
IF isEmpty(Queue) THEN
PRINT "Queue is empty!"
ELSE:
PRINT "Queue: "
FOR i = [Link] TO [Link] DO:
PRINT [Link][i] // Display each element from front to rear
END FOR
MAIN:
DECLARE Queue as an object
CALL initQueue(Queue)
REPEAT UNTIL user chooses to exit:
PRINT menu of operations:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
INPUT user's choice
SWITCH user's choice:
CASE 1:
PRINT "Enter value to enqueue:"
INPUT value
CALL enqueue(Queue, value)
CASE 2:
SET value = CALL dequeue(Queue)
IF value != -1 THEN
PRINT value " dequeued from the queue"
END IF
CASE 3:
CALL display(Queue)
CASE 4:
PRINT "Exiting the program..."
EXIT
DEFAULT:
PRINT "Invalid choice! Please try again."
END SWITCH
END REPEAT
INPUT RESTRICTED QUEUE
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Define the maximum size of the queue
// Structure to represent the queue
struct Queue {
int items[MAX];
int front, rear;
};
// Function to initialize the queue
void initQueue(struct Queue *q) {
q->front = -1;
q->rear = -1;
// Function to check if the queue is full
int isFull(struct Queue *q) {
if (q->rear == MAX - 1) {
return 1;
return 0;
// Function to check if the queue is empty
int isEmpty(struct Queue *q) {
if (q->front == -1 || q->front > q->rear) {
return 1;
return 0;
// Function to insert an element at the rear (enqueue)
void enqueue(struct Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full! Cannot enqueue %d\n", value);
} else {
if (q->front == -1) { // If the queue is empty
q->front = 0;
q->rear++;
q->items[q->rear] = value;
printf("%d enqueued to the queue\n", value);
// Function to delete an element from the front (dequeue from front)
int dequeueFront(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue from front.\n");
return -1; // Sentinel value to indicate empty queue
} else {
int dequeuedValue = q->items[q->front];
q->front++;
if (q->front > q->rear) { // Reset the queue if it becomes empty
q->front = q->rear = -1;
return dequeuedValue;
// Function to delete an element from the rear (dequeue from rear)
int dequeueRear(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! Cannot dequeue from rear.\n");
return -1; // Sentinel value to indicate empty queue
} else {
int dequeuedValue = q->items[q->rear];
q->rear--;
if (q->front > q->rear) { // Reset the queue if it becomes empty
q->front = q->rear = -1;
return dequeuedValue;
// Function to display the queue
void display(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
} else {
printf("Queue: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
printf("\n");
int main() {
struct Queue q;
initQueue(&q); // Initialize the queue
int choice, value;
while (1) {
// Menu for operations
printf("\nInput Restricted Queue Operations:\n");
printf("1. Enqueue (Insert at rear)\n");
printf("2. Dequeue from Front\n");
printf("3. Dequeue from Rear\n");
printf("4. Display Queue\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
// Enqueue operation
printf("Enter a value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
// Dequeue from Front operation
value = dequeueFront(&q);
if (value != -1) {
printf("%d dequeued from the front\n", value);
break;
case 3:
// Dequeue from Rear operation
value = dequeueRear(&q);
if (value != -1) {
printf("%d dequeued from the rear\n", value);
break;
case 4:
// Display the queue
display(&q);
break;
case 5:
// Exit the program
printf("Exiting the program...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
return 0;
PSEUDO CODE FOR INPUT RESTRICTED QUEUE
FUNCTION initQueue(Queue):
SET [Link] = -1
SET [Link] = -1
FUNCTION isFull(Queue):
IF [Link] == MAX - 1 THEN
RETURN True
ELSE
RETURN False
FUNCTION isEmpty(Queue):
IF [Link] == -1 OR [Link] > [Link] THEN
RETURN True
ELSE
RETURN False
FUNCTION enqueue(Queue, value):
IF isFull(Queue) THEN
PRINT "Queue is full! Cannot enqueue value."
ELSE:
IF [Link] == -1 THEN
SET [Link] = 0 // Set front to 0 if the queue is empty
END IF
INCREMENT [Link]
SET [Link][[Link]] = value
PRINT value " enqueued to the queue"
FUNCTION dequeueFront(Queue):
IF isEmpty(Queue) THEN
PRINT "Queue is empty! Cannot dequeue from front."
RETURN -1 // Indicating empty queue
ELSE:
SET dequeuedValue = [Link][[Link]]
INCREMENT [Link]
IF [Link] > [Link] THEN
SET [Link] = -1
SET [Link] = -1 // Reset queue if it becomes empty
END IF
RETURN dequeuedValue
FUNCTION dequeueRear(Queue):
IF isEmpty(Queue) THEN
PRINT "Queue is empty! Cannot dequeue from rear."
RETURN -1 // Indicating empty queue
ELSE:
SET dequeuedValue = [Link][[Link]]
DECREMENT [Link]
IF [Link] > [Link] THEN
SET [Link] = -1
SET [Link] = -1 // Reset queue if it becomes empty
END IF
RETURN dequeuedValue
FUNCTION display(Queue):
IF isEmpty(Queue) THEN
PRINT "Queue is empty!"
ELSE:
PRINT "Queue: "
FOR i = [Link] TO [Link] DO:
PRINT [Link][i]
END FOR
MAIN:
DECLARE Queue as an object
CALL initQueue(Queue)
REPEAT UNTIL user chooses to exit:
PRINT menu of operations:
1. Enqueue (Insert at rear)
2. Dequeue from Front
3. Dequeue from Rear
4. Display Queue
5. Exit
INPUT user's choice
SWITCH user's choice:
CASE 1:
PRINT "Enter value to enqueue:"
INPUT value
CALL enqueue(Queue, value)
CASE 2:
SET value = CALL dequeueFront(Queue)
IF value != -1 THEN
PRINT value " dequeued from the front"
END IF
CASE 3:
SET value = CALL dequeueRear(Queue)
IF value != -1 THEN
PRINT value " dequeued from the rear"
END IF
CASE 4:
CALL display(Queue)
CASE 5:
PRINT "Exiting the program..."
EXIT
DEFAULT:
PRINT "Invalid choice! Please try again."
END SWITCH
END REPEAT
TREE TRAVERSAL
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a node in the binary tree
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node with a given value
struct Node* newNode(int value) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = value;
node->left = node->right = NULL;
return node;
// Inorder Traversal (Left, Root, Right)
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left); // Traverse the left subtree
printf("%d ", root->data); // Visit the root
inorder(root->right); // Traverse the right subtree
// Preorder Traversal (Root, Left, Right)
void preorder(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data); // Visit the root
preorder(root->left); // Traverse the left subtree
preorder(root->right); // Traverse the right subtree
// Postorder Traversal (Left, Right, Root)
void postorder(struct Node* root) {
if (root != NULL) {
postorder(root->left); // Traverse the left subtree
postorder(root->right); // Traverse the right subtree
printf("%d ", root->data); // Visit the root
// Function to insert a new node in the binary tree
struct Node* insert(struct Node* root, int value) {
// If the tree is empty, create a new node and return it
if (root == NULL) {
return newNode(value);
// Otherwise, insert the value in the left or right subtree based on user choice
printf("Enter 'L' to insert %d to the left or 'R' to insert it to the right of %d: ", value, root->data);
char direction;
scanf(" %c", &direction); // Read the direction input
if (direction == 'L' || direction == 'l') {
root->left = insert(root->left, value); // Insert in the left subtree
} else if (direction == 'R' || direction == 'r') {
root->right = insert(root->right, value); // Insert in the right subtree
} else {
printf("Invalid direction. Please enter 'L' or 'R'.\n");
return root;
}
int main() {
struct Node* root = NULL;
int value, n, i;
printf("Enter the number of nodes you want to insert: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter node value: ");
scanf("%d", &value);
if (root == NULL) {
// Create the root node if the tree is empty
root = newNode(value);
} else {
// Insert the node into the tree
root = insert(root, value);
// Print tree traversals
printf("\nInorder Traversal: ");
inorder(root);
printf("\n");
printf("Preorder Traversal: ");
preorder(root);
printf("\n");
printf("Postorder Traversal: ");
postorder(root);
printf("\n");
return 0;
PSEUDO CODE FOR TREE TRAVERSAL
FUNCTION newNode(value):
CREATE a new node with given value
SET [Link] = NULL
SET [Link] = NULL
RETURN node
FUNCTION insert(root, value):
IF root IS NULL THEN
RETURN newNode(value)
END IF
PRINT "Enter 'L' to insert [value] to the left or 'R' to insert it to the right of [[Link]]: "
READ direction
IF direction == 'L' OR direction == 'l' THEN
SET [Link] = insert([Link], value) // Insert to the left
ELSE IF direction == 'R' OR direction == 'r' THEN
SET [Link] = insert([Link], value) // Insert to the right
ELSE
PRINT "Invalid direction. Please enter 'L' or 'R'."
END IF
RETURN root
FUNCTION inorder(root):
IF root IS NOT NULL THEN
CALL inorder([Link]) // Traverse the left subtree
PRINT [Link] // Visit the root
CALL inorder([Link]) // Traverse the right subtree
END IF
FUNCTION preorder(root):
IF root IS NOT NULL THEN
PRINT [Link] // Visit the root
CALL preorder([Link]) // Traverse the left subtree
CALL preorder([Link]) // Traverse the right subtree
END IF
FUNCTION postorder(root):
IF root IS NOT NULL THEN
CALL postorder([Link]) // Traverse the left subtree
CALL postorder([Link]) // Traverse the right subtree
PRINT [Link] // Visit the root
END IF
MAIN:
PRINT "Enter the number of nodes you want to insert: "
READ n // Get number of nodes to insert
SET root = NULL
FOR i = 1 TO n DO:
PRINT "Enter node value: "
READ value
IF root IS NULL THEN
SET root = newNode(value) // Set the root if tree is empty
ELSE
SET root = insert(root, value) // Insert value into the tree
END IF
END FOR
PRINT "Inorder Traversal: "
CALL inorder(root)
PRINT "Preorder Traversal: "
CALL preorder(root)
PRINT "Postorder Traversal: "
CALL postorder(root)
MINIMUM SPANNING TREE
#include <stdio.h>
#include <limits.h>
#define MAX_VERTICES 10 // Maximum number of vertices
// Function to find the vertex with the minimum key value that has not been included in the MST
int minKey(int key[], int mstSet[], int V) {
int min = INT_MAX, minIndex;
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
minIndex = v;
return minIndex;
// Function to print the constructed MST stored in parent[]
void printMST(int parent[], int graph[MAX_VERTICES][MAX_VERTICES], int V) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
// Function to implement Prim's algorithm to find the MST of a graph
void primMST(int graph[MAX_VERTICES][MAX_VERTICES], int V) {
int parent[V]; // Array to store the MST
int key[V]; // Key values to pick minimum weight edge
int mstSet[V]; // To represent the set of vertices included in the MST
// Initialize all keys as INFINITE and mstSet[] as false
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0; // All vertices are not included in the MST
// Always include the first vertex in the MST
key[0] = 0;
parent[0] = -1; // First node is always the root of MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices not yet included in the MST
int u = minKey(key, mstSet, V);
// Add the picked vertex to the MST Set
mstSet[u] = 1;
// Update key value and parent index of the adjacent vertices of the picked vertex
for (int v = 0; v < V; v++) {
// graph[u][v] is non-zero only for adjacent vertices of u
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] != 0 && mstSet[v] == 0 && graph[u][v] < key[v]) {
key[v] = graph[u][v];
parent[v] = u;
// Print the constructed MST
printMST(parent, graph, V);
int main() {
int V, E;
// Prompt the user for the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &V);
// Adjacency matrix to store the graph
int graph[MAX_VERTICES][MAX_VERTICES] = {0};
// Prompt the user for the number of edges
printf("Enter the number of edges: ");
scanf("%d", &E);
// Input the edges and their weights
printf("Enter the edges in the format: vertex1 vertex2 weight\n");
for (int i = 0; i < E; i++) {
int u, v, weight;
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &u, &v, &weight);
graph[u][v] = weight; // Undirected graph: Add weight in both directions
graph[v][u] = weight;
// Call Prim's algorithm to find the MST of the graph
printf("\nMinimum Spanning Tree (MST):\n");
primMST(graph, V);
return 0;
Output: Enter the number of vertices: 5
Enter the number of edges: 7
Enter the edges in the format: vertex1 vertex2 weight
Edge 1: 0 1 2
Edge 2: 0 3 6
Edge 3: 1 2 3
Edge 4: 1 3 8
Edge 5: 1 4 5
Edge 6: 2 4 7
Edge 7: 3 4 9
Minimum Spanning Tree (MST):
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
PSEUDO CODE OF MINIMUM SPANNING TREE
FUNCTION minKey(key[], mstSet[], V):
SET min = INFINITY
SET minIndex = -1
FOR each vertex v from 0 to V-1 DO:
IF mstSet[v] is NOT included in MST AND key[v] < min THEN:
SET min = key[v]
SET minIndex = v
END FOR
RETURN minIndex
FUNCTION printMST(parent[], graph[][], V):
PRINT "Edge Weight"
FOR i = 1 TO V-1 DO:
PRINT "parent[i] - i graph[i][parent[i]]"
END FOR
FUNCTION primMST(graph[][], V):
DECLARE parent[V] // Array to store the MST
DECLARE key[V] // Key values to pick minimum weight edge
DECLARE mstSet[V] // To represent the set of vertices included in the MST
// Initialize all keys as INFINITY and mstSet[] as false
FOR i = 0 TO V-1 DO:
key[i] = INFINITY
mstSet[i] = 0 // All vertices are not included in the MST
END FOR
// Start with vertex 0 in the MST
key[0] = 0
parent[0] = -1 // The first node is always the root of the MST
// The MST will have V vertices
FOR count = 0 TO V-1 DO:
// Pick the vertex u with the minimum key value that is not yet included in MST
SET u = minKey(key, mstSet, V)
// Include u in the MST set
mstSet[u] = 1
// Update the key and parent values for adjacent vertices of u
FOR each vertex v from 0 to V-1 DO:
IF graph[u][v] != 0 AND mstSet[v] == 0 AND graph[u][v] < key[v] THEN:
key[v] = graph[u][v]
parent[v] = u
END IF
END FOR
END FOR
// Print the edges of the MST
CALL printMST(parent, graph, V)
MAIN:
PRINT "Enter the number of vertices (V): "
READ V
PRINT "Enter the number of edges (E): "
READ E
// Initialize the graph as a 2D array of zeros (adjacency matrix)
DECLARE graph[V][V] = {0}
// Input edges and their weights
FOR i = 0 TO E-1 DO:
PRINT "Enter edge (u, v, weight): "
READ u, v, weight
graph[u][v] = weight
graph[v][u] = weight // As the graph is undirected
END FOR
// Call Prim's algorithm to find the MST of the graph
CALL primMST(graph, V)