0% found this document useful (0 votes)
5 views29 pages

Search and Sort Algorithms in C

Uploaded by

Devansh Bhatia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Search and Sort Algorithms in C

Uploaded by

Devansh Bhatia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program 1

Linear and Binary Search


#include <stdio.h>

int main() {
int arr[100], n, key, i, low, high, mid, found = 0;

printf("Enter number of elements: ");


scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

printf("Enter element to search: ");


scanf("%d", &key);

// Linear Search
for(i = 0; i < n; i++) {
if(arr[i] == key) {
printf("Linear Search: Found at position %d\n", i + 1);
found = 1;
break;
}
}
if(!found)
printf("Linear Search: Not found\n");

// Binary Search (requires sorted array)


low = 0;
high = n - 1;
found = 0;

while(low <= high) {


mid = (low + high) / 2;
if(arr[mid] == key) {
printf("Binary Search: Found at position %d\n", mid + 1);
found = 1;
break;
} else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}

if(!found)
printf("Binary Search: Not found\n");
return 0;
}

Page 1 of 29
Program 2
Selection, Bubble, Insertion Sort
#include <stdio.h>

int main() {
int arr[100], n, i, j, temp;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

// ---------- Selection Sort ----------


for(i = 0; i < n - 1; i++) {
for(j = i + 1; j < n; j++) {
if(arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

printf("Array after Selection Sort: ");


for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

// ---------- Bubble Sort ----------


printf("Enter elements again for Bubble Sort:\n");
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

for(i = 0; i < n - 1; i++) {


for(j = 0; j < n - 1 - i; j++) {
if(arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

printf("Array after Bubble Sort: “);

for(i = 0; i < n; i++)

Page 2 of 29
printf("%d ", arr[i]);
printf("\n");

// ---------- Insertion Sort ----------


printf("Enter elements again for Insertion Sort:\n");
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

for(i = 1; i < n; i++) {


temp = arr[i];
j = i - 1;
while(j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}

printf("Array after Insertion Sort: ");


for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

return 0;
}

Page 3 of 29
Program 3
Merge Sort
#include <stdio.h>

// Function to merge two parts of the array


void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1; // size of left part
int n2 = right - mid; // size of right part
int L[100], R[100]; // temporary arrays

// Copy data to temporary arrays


for(i = 0; i < n1; i++)
L[i] = arr[left + i];
for(j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// Merge the two arrays back into arr[]


i = 0;
j = 0;
k = left;

while(i < n1 && j < n2) {


if(L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy remaining elements of L[]


while(i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy remaining elements of R[]


while(j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Function to divide the array into smaller parts

Page 4 of 29
void mergeSort(int arr[], int left, int right) {
if(left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid); // sort first half
mergeSort(arr, mid + 1, right); // sort second half
merge(arr, left, mid, right); // merge the two halves
}
}

int main() {
int arr[100], n, i;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

mergeSort(arr, 0, n - 1);

printf("Array after Merge Sort: ");


for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

return 0;
}

Page 5 of 29
Program 4
Stack Operations
#include <stdio.h>
#include <string.h>

#define SIZE 100

int stack[SIZE];
int top = -1;

// ---------- Stack Functions ----------


void push(int value) {
if(top == SIZE - 1)
printf("Stack is Full (Overflow)\n");
else
stack[++top] = value;
}

int pop() {
if(top == -1) {
printf("Stack is Empty (Underflow)\n");
return -1;
} else
return stack[top--];
}

void display() {
int i;
if(top == -1)
printf("Stack is Empty\n");
else {
printf("Stack elements: ");
for(i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}
}

// ---------- Reverse String Function ----------


void reverseString(char str[]) {
int i;
char chStack[SIZE];
int topChar = -1;

for(i = 0; str[i] != '\0'; i++)


chStack[++topChar] = str[i];

printf("Reversed string: ");


while(topChar != -1)

Page 6 of 29
printf("%c", chStack[topChar--]);
printf("\n");
}

// ---------- Main Function ----------


int main() {
int choice, value;
char str[100];

while(1) {
printf("\n--- STACK MENU ---\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Reverse a String using Stack\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if(choice == 1) {
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
}
else if(choice == 2) {
value = pop();
if(value != -1)
printf("Popped: %d\n", value);
}
else if(choice == 3) {
display();
}
else if(choice == 4) {
printf("Enter a string: ");
scanf(" %[^\n]", str); // read string with spaces
reverseString(str);
}
else if(choice == 0) {
break;
}
else {
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

Page 7 of 29
Program 5
Depth First Search, Breadth First Search
#include <stdio.h>

#define MAX 10

int graph[MAX][MAX]; // adjacency matrix


int visited[MAX]; // visited array
int queue[MAX]; // queue for BFS
int front = 0, rear = -1;

// ---------- Depth First Search (DFS) ----------


void DFS(int vertex, int n) {
int i;
visited[vertex] = 1;
printf("%d ", vertex);

for(i = 1; i <= n; i++) {


if(graph[vertex][i] == 1 && visited[i] == 0)
DFS(i, n);
}
}

// ---------- Breadth First Search (BFS) ----------


void BFS(int start, int n) {
int i;
for(i = 1; i <= n; i++)
visited[i] = 0;

front = 0;
rear = -1;
queue[++rear] = start;
visited[start] = 1;

while(front <= rear) {


int vertex = queue[front++];
printf("%d ", vertex);

for(i = 1; i <= n; i++) {


if(graph[vertex][i] == 1 && visited[i] == 0) {
queue[++rear] = i;
visited[i] = 1;
}
}
}
}

int main() {
int n, i, j, start;

Page 8 of 29
printf("Enter number of vertices: ");
scanf("%d", &n);

printf("Enter adjacency matrix (use 1 for edge, 0 for no edge):\n");


for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
scanf("%d", &graph[i][j]);
}
}

printf("Enter starting vertex: ");


scanf("%d", &start);

// DFS
for(i = 1; i <= n; i++)
visited[i] = 0;

printf("DFS Traversal: ");


DFS(start, n);
printf("\n");

// BFS
printf("BFS Traversal: ");
BFS(start, n);
printf("\n");

return 0;
}

Page 9 of 29
Program 6
Knapsack Problem using Greedy Method
#include <stdio.h>

int main() {
int n, i, j;
double capacity;
double weight[100], value[100], ratio[100];
double tempD;
int tempI; // not needed but kept for style similarity

printf("Enter number of items: ");


scanf("%d", &n);

printf("Enter knapsack capacity: ");


scanf("%lf", &capacity);

printf("Enter weight and value for each item:\n");


for(i = 0; i < n; i++) {
printf("Item %d (weight value): ", i + 1);
scanf("%lf %lf", &weight[i], &value[i]);
ratio[i] = value[i] / weight[i];
}

// Sort items by ratio (value/weight) in descending order using simple bubble sort
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - 1 - i; j++) {
if(ratio[j] < ratio[j + 1]) {
// swap ratio
tempD = ratio[j]; ratio[j] = ratio[j + 1]; ratio[j + 1] = tempD;
// swap weight
tempD = weight[j]; weight[j] = weight[j + 1]; weight[j + 1] = tempD;
// swap value
tempD = value[j]; value[j] = value[j + 1]; value[j + 1] = tempD;
}
}
}

// Greedy pick: take full item if possible, else take fraction


double totalValue = 0.0;
double remaining = capacity;

for(i = 0; i < n; i++) {


if(remaining == 0.0)
break;

if(weight[i] <= remaining) {


totalValue += value[i];
remaining -= weight[i];

Page 10 of 29
} else {
double fraction = remaining / weight[i];
totalValue += value[i] * fraction;
remaining = 0.0;
}
}

printf("Maximum value (fractional allowed): %.2f\n", totalValue);


return 0;
}

Page 11 of 29
Program 7
Single Source Shortest Path
#include <stdio.h>

#define MAX 100


#define INF 1000000000

int main() {
int n, i, j, start;
int graph[MAX][MAX];
int dist[MAX];
int visited[MAX];

printf("Enter number of vertices: ");


scanf("%d", &n);

printf("Enter adjacency matrix (0 means no edge):\n");


for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
scanf("%d", &graph[i][j]);
}
}

printf("Enter source vertex: ");


scanf("%d", &start);

for(i = 1; i <= n; i++) {


dist[i] = INF;
visited[i] = 0;
}
dist[start] = 0;

// Dijkstra's algorithm
for(i = 1; i <= n - 1; i++) {
int u = -1;
int minDist = INF;

// pick the unvisited vertex with smallest distance


for(j = 1; j <= n; j++) {
if(!visited[j] && dist[j] < minDist) {
minDist = dist[j];
u = j;
}
}

if(u == -1) // remaining vertices are unreachable


break;

visited[u] = 1;

Page 12 of 29
// relax edges from u
for(j = 1; j <= n; j++) {
if(graph[u][j] != 0) { // there is an edge u->j
if(dist[u] + graph[u][j] < dist[j]) {
dist[j] = dist[u] + graph[u][j];
}
}
}
}

printf("Shortest distances from %d:\n", start);


for(i = 1; i <= n; i++) {
if(dist[i] == INF)
printf("to %d = INF\n", i);
else
printf("to %d = %d\n", i, dist[i]);
}

return 0;
}

Page 13 of 29
Program 8
Knapsack Problem using Dynamic Programming
#include <stdio.h>

#define MAXN 100


#define MAXW 1000

int main() {
int n, W;
int wt[MAXN + 1], val[MAXN + 1];
int dp[MAXN + 1][MAXW + 1];
int i, w;

printf("Enter number of items: ");


scanf("%d", &n);

printf("Enter knapsack capacity: ");


scanf("%d", &W);

if (W > MAXW) {
printf("Capacity too large (max %d). Using %d.\n", MAXW, MAXW);
W = MAXW;
}

printf("Enter weight and value of each item:\n");


for (i = 1; i <= n; i++) {
printf("Item %d (weight value): ", i);
scanf("%d %d", &wt[i], &val[i]);
}

// Initialize DP table
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
dp[i][w] = 0;
}
}

// Fill DP table
for (i = 1; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (wt[i] <= w) {
int include = val[i] + dp[i - 1][w - wt[i]];
int exclude = dp[i - 1][w];
dp[i][w] = (include > exclude) ? include : exclude;
} else {
dp[i][w] = dp[i - 1][w];
}
}
}

Page 14 of 29
// Result
printf("Maximum value: %d\n", dp[n][W]);

// (Optional) Recover chosen items


printf("Items chosen (by index): ");
i = n; w = W;
while (i > 0 && w >= 0) {
if (dp[i][w] != dp[i - 1][w]) {
// item i was taken
printf("%d ", i);
w = w - wt[i];
}
i--;
}
printf("\n");

return 0;
}

Page 15 of 29
Program 9
N-Queens’s Problem using Back Tracking
#include <stdio.h>

#define MAX 12 // you can increase up to what your system allows

int n;
int board[MAX][MAX];
int solutions = 0;

// Check if placing a queen at (row, col) is safe


int isSafe(int row, int col) {
int i, j;

// Check same column above


for(i = 0; i < row; i++)
if(board[i][col] == 1)
return 0;

// Check upper-left diagonal


i = row - 1; j = col - 1;
while(i >= 0 && j >= 0) {
if(board[i][j] == 1) return 0;
i--; j--;
}

// Check upper-right diagonal


i = row - 1; j = col + 1;
while(i >= 0 && j < n) {
if(board[i][j] == 1) return 0;
i--; j++;
}

return 1; // safe
}

// Try to place queens row by row (Backtracking)


void solve(int row) {
int col, i, j;

// If all rows are filled, we found a solution


if(row == n) {
solutions++;

printf("\nSolution %d:\n", solutions);


for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(board[i][j] == 1) printf("Q ");
else printf(". ");

Page 16 of 29
}
printf("\n");
}
return; // continue searching for more solutions
}

// Try to place a queen in each column of this row


for(col = 0; col < n; col++) {
if(isSafe(row, col)) {
board[row][col] = 1; // place queen
solve(row + 1); // go to next row
board[row][col] = 0; // backtrack
}
}
}

int main() {
int i, j;

printf("Enter N for N-Queens (<= %d): ", MAX);


scanf("%d", &n);

if(n <= 0 || n > MAX) {


printf("Invalid N\n");
return 0;
}

// Initialize board to 0
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
board[i][j] = 0;

solve(0);

if(solutions == 0)
printf("No solutions exist for N = %d\n", n);
else
printf("\nTotal solutions: %d\n", solutions);

return 0;
}

Page 17 of 29
Program 10
Quick Sort Algorithm
#include <stdio.h>

// Function to swap two elements


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to partition the array


int partition(int arr[], int low, int high) {
int pivot = arr[high]; // choosing last element as pivot
int i = low - 1;
int j;
for(j = low; j < high; j++) {
if(arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Recursive function for Quick Sort


void quickSort(int arr[], int low, int high) {
if(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); // sort left side
quickSort(arr, pi + 1, high); // sort right side
}
}
int main() {
int arr[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

quickSort(arr, 0, n - 1);
printf("Array after Quick Sort: ");
for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

return 0;}

Page 18 of 29
Program 11
Queue Operations
#include <stdio.h>

#define SIZE 100

int queue[SIZE];
int front = -1;
int rear = -1;

// Function to insert element in queue


void enqueue(int value) {
if(rear == SIZE - 1) {
printf("Queue is Full (Overflow)\n");
} else {
if(front == -1) // first element
front = 0;
rear++;
queue[rear] = value;
printf("Inserted: %d\n", value);
}
}

// Function to delete element from queue


void dequeue() {
if(front == -1 || front > rear) {
printf("Queue is Empty (Underflow)\n");
} else {
printf("Deleted: %d\n", queue[front]);
front++;
}
}

// Function to display queue elements


void display() {
int i;
if(front == -1 || front > rear) {
printf("Queue is Empty\n");
} else {
printf("Queue elements: ");
for(i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
}

int main() {
int choice, value;

Page 19 of 29
while(1) {
printf("\n--- QUEUE MENU ---\n");
printf("1. Enqueue (Insert)\n");
printf("2. Dequeue (Delete)\n");
printf("3. Display\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if(choice == 1) {
printf("Enter value to insert: ");
scanf("%d", &value);
enqueue(value);
}
else if(choice == 2) {
dequeue();
}
else if(choice == 3) {
display();
}
else if(choice == 0) {
break;
}
else {
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

Page 20 of 29
Program 12
Singly Linked List Operations
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};

struct Node *head = NULL;

// Function to insert a new node at the end


void insertNode(int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if(head == NULL) {
head = newNode;
} else {
struct Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
printf("Inserted: %d\n", value);
}

// Function to delete a node by value


void deleteNode(int value) {
struct Node *temp = head, *prev = NULL;

if(head == NULL) {
printf("List is Empty\n");
return;
}

// If head node itself holds the value


if(temp != NULL && temp->data == value) {
head = temp->next;
free(temp);
printf("Deleted: %d\n", value);
return;
}

// Search for the node to delete


while(temp != NULL && temp->data != value) {
prev = temp;

Page 21 of 29
temp = temp->next;
}

if(temp == NULL) {
printf("Value not found in list\n");
return;
}

prev->next = temp->next;
free(temp);
printf("Deleted: %d\n", value);
}

// Function to display all nodes


void displayList() {
struct Node *temp = head;

if(temp == NULL) {
printf("List is Empty\n");
return;
}

printf("Linked List: ");


while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to search for a value


void searchNode(int value) {
struct Node *temp = head;
int position = 1;

while(temp != NULL) {
if(temp->data == value) {
printf("Value %d found at position %d\n", value, position);
return;
}
temp = temp->next;
position++;
}

printf("Value not found in list\n");


}

int main() {
int choice, value;

while(1) {
printf("\n--- LINKED LIST MENU ---\n");
printf("1. Insert Node\n");

Page 22 of 29
printf("2. Delete Node\n");
printf("3. Display List\n");
printf("4. Search Node\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if(choice == 1) {
printf("Enter value to insert: ");
scanf("%d", &value);
insertNode(value);
}
else if(choice == 2) {
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(value);
}
else if(choice == 3) {
displayList();
}
else if(choice == 4) {
printf("Enter value to search: ");
scanf("%d", &value);
searchNode(value);
}
else if(choice == 0) {
break;
}
else {
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

Page 23 of 29
Program 13
Stack and Queue using Lists
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};

struct Node *top = NULL; // For Stack


struct Node *front = NULL; // For Queue
struct Node *rear = NULL;

// ---------- STACK FUNCTIONS ----------

// Push element onto stack


void push(int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = top;
top = newNode;
printf("Pushed: %d\n", value);
}

// Pop element from stack


void pop() {
if(top == NULL) {
printf("Stack is Empty\n");
} else {
struct Node *temp = top;
printf("Popped: %d\n", top->data);
top = top->next;
free(temp);
}
}

// Display stack elements


void displayStack() {
if(top == NULL) {
printf("Stack is Empty\n");
} else {
struct Node *temp = top;
printf("Stack elements (Top to Bottom): ");
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");

Page 24 of 29
}
}

// ---------- QUEUE FUNCTIONS ----------

// Enqueue (Insert) element into queue


void enqueue(int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if(rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
printf("Enqueued: %d\n", value);
}

// Dequeue (Delete) element from queue


void dequeue() {
if(front == NULL) {
printf("Queue is Empty\n");
} else {
struct Node *temp = front;
printf("Dequeued: %d\n", front->data);
front = front->next;
if(front == NULL)
rear = NULL;
free(temp);
}
}

// Display queue elements


void displayQueue() {
if(front == NULL) {
printf("Queue is Empty\n");
} else {
struct Node *temp = front;
printf("Queue elements (Front to Rear): ");
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}

// ---------- MAIN FUNCTION ----------


int main() {
int choice, value, structureChoice;

Page 25 of 29
while(1) {
printf("\n--- MAIN MENU ---\n");
printf("1. Stack Operations\n");
printf("2. Queue Operations\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &structureChoice);

if(structureChoice == 1) {
while(1) {
printf("\n--- STACK MENU ---\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("0. Back to Main Menu\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if(choice == 1) {
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
} else if(choice == 2) {
pop();
} else if(choice == 3) {
displayStack();
} else if(choice == 0) {
break;
} else {
printf("Invalid choice! Try again.\n");
}
}
}

else if(structureChoice == 2) {
while(1) {
printf("\n--- QUEUE MENU ---\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("0. Back to Main Menu\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if(choice == 1) {
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(value);
} else if(choice == 2) {
dequeue();
} else if(choice == 3) {
displayQueue();
} else if(choice == 0) {

Page 26 of 29
break;
} else {
printf("Invalid choice! Try again.\n");
}
}
}

else if(structureChoice == 0) {
break;
}

else {
printf("Invalid choice! Try again.\n");
}
}

return 0;
}

Page 27 of 29
Program 14
Binary Tree Traversal
#include <stdio.h>
#include <stdlib.h>

// Node structure
struct Node {
int data;
struct Node *left;
struct Node *right;
};

// Create a new node


struct Node* createNode(int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Traversals
void preorder(struct Node *root) {
if(root == NULL) return;
printf("%d ", root->data); // Visit root
preorder(root->left); // Visit left
preorder(root->right); // Visit right
}

void inorder(struct Node *root) {


if(root == NULL) return;
inorder(root->left); // Visit left
printf("%d ", root->data); // Visit root
inorder(root->right); // Visit right
}

void postorder(struct Node *root) {


if(root == NULL) return;
postorder(root->left); // Visit left
postorder(root->right); // Visit right
printf("%d ", root->data); // Visit root
}

int main() {
// Build a simple sample tree
// 1
// / \
// 2 3
// / \ / \

Page 28 of 29
// 4 5 6 7

struct Node *root = createNode(1);


root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);

printf("Preorder : ");
preorder(root);
printf("\n");

printf("Inorder : ");
inorder(root);
printf("\n");

printf("Postorder : ");
postorder(root);
printf("\n");

return 0;
}

Page 29 of 29

You might also like