0% found this document useful (0 votes)
2 views6 pages

BFS and DFS For Trees

The document contains C code for implementing breadth-first search (BFS) and depth-first search (DFS) traversals on a general tree data structure. It defines the necessary data structures, such as tree nodes, queues, and stacks, and includes functions for creating nodes, adding children, and performing the traversals. The main function demonstrates building a tree and executing both BFS and DFS algorithms.

Uploaded by

maariaam.gh
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)
2 views6 pages

BFS and DFS For Trees

The document contains C code for implementing breadth-first search (BFS) and depth-first search (DFS) traversals on a general tree data structure. It defines the necessary data structures, such as tree nodes, queues, and stacks, and includes functions for creating nodes, adding children, and performing the traversals. The main function demonstrates building a tree and executing both BFS and DFS algorithms.

Uploaded by

maariaam.gh
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
You are on page 1/ 6

1

////////BFS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 100 // Maximum size for the queue

// Tree node definition for a general tree


typedef struct TreeNode {
int data; // Node value
struct TreeNode *firstChild; // Pointer to the first child
struct TreeNode *nextSiblings; // Pointer to the next sibling
} TreeNode;

// Function to create a new tree node


TreeNode* createNode(int data) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->firstChild = NULL;
node->nextSiblings = NULL;
return node;
}

// Adds a child to a parent node (as last sibling if others exist)


void addChild(TreeNode *parent, TreeNode *child) {
if(parent->firstChild == NULL) {
parent->firstChild = child;
} else {
TreeNode *c = parent->firstChild;
while(c->nextSiblings != NULL) {
c = c->nextSiblings;
}
c->nextSiblings = child;
}
}

// Queue structure for BFS traversal


typedef struct Queue {
TreeNode *arr[MAX_SIZE]; // Array of TreeNode pointers
int front; // Index of the front of the queue
int rear; // Index of the rear of the queue
} Queue;

// Initialize the queue


void init(Queue *qu) {
qu->front = -1;
qu->rear = -1;
}
2

// Check if the queue is empty


bool isEmpty(Queue *qu) {
return (qu->front == -1 || qu->front > qu->rear);
}

// Check if the queue is full


bool isFull(Queue *qu) {
return (qu->rear == MAX_SIZE - 1);
}

// Add a node to the queue


void enqueue(Queue *qu, TreeNode *node) {
if (isFull(qu)) {
printf("Queue is full\n");
return;
}
if (isEmpty(qu)) {
qu->front = 0;
}
qu->arr[++qu->rear] = node;
}

// Remove a node from the queue


void dequeue(Queue *qu) {
if (isEmpty(qu)) {
printf("Queue is empty\n");
return;
}
qu->front++;
if (qu->front > qu->rear) {
init(qu); // Reset the queue
}
}

// Get the node at the front of the queue


TreeNode* front(Queue *qu) {
if (isEmpty(qu)) {
printf("Queue is empty\n");
return NULL;
}
return qu->arr[qu->front];
}
3

// Breadth-First Search (BFS) traversal of the tree


void bfs(TreeNode *head) {
if (head == NULL) {
return;
}
Queue q;
init(&q); // Initialize queue
enqueue(&q, head); // Start with the root node

while(!isEmpty(&q)) {
TreeNode *t = front(&q); // Get current node
printf("%d ", t->data); // Print its data
dequeue(&q); // Remove it from queue

// Enqueue all its children


TreeNode *c = t->firstChild;
while (c) {
enqueue(&q, c);
c = c->nextSiblings;
}
}
}

// Main function to build a tree and perform BFS


int main() {
TreeNode *n1 = createNode(1);
TreeNode *n2 = createNode(2);
TreeNode *n3 = createNode(3);
TreeNode *n4 = createNode(4);
TreeNode *n5 = createNode(5);
TreeNode *n6 = createNode(6);

// Constructing the tree


addChild(n1, n2); // 1 → 2
addChild(n1, n3); // 1 → 3
addChild(n1, n4); // 1 → 4

addChild(n2, n5); // 2 → 5
addChild(n3, n6); // 3 → 6

// Perform BFS traversal


bfs(n1);

return 0;
}
4

///////////DFS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 100 // Maximum size for the stack


// Definition of a general tree node
typedef struct TreeNode {
int data;
struct TreeNode *firstChild;
struct TreeNode *nextSiblings;
} TreeNode;

// Create a new tree node with given data


TreeNode* createNode(int data) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->firstChild = NULL;
node->nextSiblings = NULL;
return node;
}

// Add a child node to the parent (append as last sibling)


void addChild(TreeNode *parent, TreeNode *child) {
if (parent->firstChild == NULL) {
parent->firstChild = child;
} else {
TreeNode *c = parent->firstChild;
while (c->nextSiblings != NULL) {
c = c->nextSiblings;
}
c->nextSiblings = child;
}
}

// Stack structure for DFS


typedef struct Stack {
TreeNode* arr[MAX_SIZE];
int top_index;
} Stack;

// Initialize the stack


void init(Stack *st) {
st->top_index = -1;
}

// Check if the stack is empty


bool isEmpty(Stack *st) {
return st->top_index == -1;
}
5

// Check if the stack is full


bool isFull(Stack *st) {
return st->top_index == MAX_SIZE - 1;
}

// Push a node onto the stack


void push(Stack *st, TreeNode *value) {
if (isFull(st)) {
printf("Stack is full\n");
return;
}
st->arr[++st->top_index] = value;
}

// Pop a node from the stack


void pop(Stack *st) {
if (isEmpty(st)) {
printf("Stack is empty\n");
return;
}
st->top_index--;
}

// Get the top element of the stack


TreeNode* top(Stack *st) {
if (isEmpty(st)) {
printf("Stack is empty\n");
return NULL;
}
return st->arr[st->top_index];
}
6

// Iterative Depth-First Search (DFS) traversal


void dfs(TreeNode *head){
if (head == NULL) {
return;
}

Stack s;
init(&s); // Initialize stack
push(&s, head); // Start from root

while (!isEmpty(&s)) {
TreeNode *t = top(&s);
printf("%d ", t->data); // Visit node
pop(&s);

TreeNode* children[MAX_SIZE]; // Temporary array to reverse


children order
int count = 0;

TreeNode *c = t->firstChild;
while (c) {
children[count++] = c;
c = c->nextSiblings;
}
// Push children onto stack in reverse order so the leftmost
child is processed first
for (int i = count - 1; i >= 0; i--) {
push(&s, children[i]);
}
}
}

// Main function: builds a tree and runs DFS


int main() {
TreeNode *n1 = createNode(1);
TreeNode *n2 = createNode(2);
TreeNode *n3 = createNode(3);
TreeNode *n4 = createNode(4);
TreeNode *n5 = createNode(5);
TreeNode *n6 = createNode(6);
// Build the tree structure
addChild(n1, n2);
addChild(n1, n3);
addChild(n1, n4);
addChild(n2, n5);
addChild(n3, n6);
// Perform DFS traversal
dfs(n1);
return 0;
}

You might also like