0% found this document useful (0 votes)
45 views209 pages

Data Structure - Ppt-Notes

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)
45 views209 pages

Data Structure - Ppt-Notes

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/ 209

DATA STRUCTURES

AND APPLICATIONS
Course Details
• Subject Code: BCS304

• Subject Name: Data Structures and Applications

• Teaching Hours/Week: 3

• Total Hours of Pedagogy: 40 hours

• Credits: 03

• Marks:
– CIE (Continuous Internal Evaluation): 50 marks

– SEE (Semester End Examination): 50 marks

– Total Marks: 100 marks

• Exam Duration: 3 hours


Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
course objectives

• To explain the fundamentals of data structures and their applications.

• To illustrate the representation of different data structures such as Stacks, Queues, Linked Lists,

Trees, and Graphs.

• To design and develop solutions to problems using linear data structures.

• To discuss the applications of non-linear data structures in problem-solving.

• To introduce advanced data structure concepts such as Hashing and Optimal Binary Search Trees.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


LINKED LISTS

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A Linked List is a linear data structure in which
elements, called nodes, may not store in contiguous
memory locations. Each node contains two parts:
1.Data: The actual value of the node.
2.Link (Pointer): A reference to the next node in the
sequence. Head Node

A B C D NULL

Data Link
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Advantages of Linked Lists:
1.Dynamic Size: The size of a linked list can grow or shrink dynamically,
making it more flexible than arrays.
2.Efficient Insertions/Deletions: Insertion and deletion operations are
more efficient as there is no need for shifting elements, unlike arrays.

Disadvantages:
1.Random Access Not Possible: Linked lists don't support direct access to
elements by index, making random access inefficient compared to arrays.
2.Extra Memory Overhead: Each node requires additional memory for
storing the pointer to the next node.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Types of Linked Lists

Linked lists can be classified based on their structure and how the
nodes are connected.
The three primary types of linked lists are:
1.Singly Linked List
2.Doubly Linked List
3.Circular Linked List

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Singly Linked List
• Structure: In a singly linked list, each node contains:
– Data: The value or information of the node.
– Link: A pointer that points to the next node in the sequence.
• Connection: The nodes are connected in a linear sequence, with each node
pointing to the next node. The last node has its pointer set to NULL,
indicating the end of the list.

Head Node

A B C D NULL

Data Next
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
• Operations:
– Insertion: Can be performed at the beginning, middle, or end of the list.
– Deletion: Nodes can be deleted from the front, middle, or end.
– Traversal: Starts from the head and continues until NULL is encountered.
• Advantages:
– Efficient memory usage as it requires only one pointer per node.
– Easy to implement and suitable for simple applications.
• Disadvantages:
– Cannot be traversed backward, limiting access to the previous node.
– Finding the previous node requires traversal from the head.
• Use Case: Implementing stacks, queues, or simple dynamic lists.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Doubly Linked List
• Structure: In a doubly linked list, each node contains:
o Data: The value or information of the node.
o Prev: A pointer that points to the previous node.
o Next: A pointer that points to the next node in the sequence.
• Connection: The nodes are connected in both forward and backward directions, allowing for
traversal in either direction. The first node’s Prev pointer is set to NULL, and the last node’s Next
pointer is also set to NULL.

Head Node

NULL A B C D NULL

Prev Data Next


Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
• Operations:
o Insertion: Can be performed at the beginning, middle, or end with ease, as it can
traverse in both directions.
o Deletion: Nodes can be easily removed from any position without the need for
searching for the previous node.
o Traversal: Can be done both forward and backward.
• Advantages:
o Easier to delete and traverse in both directions.
o More flexibility in managing nodes.
• Disadvantages:
o Requires more memory per node (two pointers instead of one).
o Slightly more complex to implement compared to singly linked lists.
• Use Case: Navigating browser history (forward/backward), implementing undo/redo
functionality in software, and managing playlists.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Circular Linked List
a. Circular Singly Linked List

Structure: Similar to a singly linked list, but the last node’s Next pointer
points back to the first node, forming a circle.

Head Node

A B C D
Data Next
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
• Operations:
– Insertion: Can be performed at the beginning, middle, or end. Since the list is circular, insertion at the end
requires updating the last node’s pointer to point to the new node, which in turn points back to the first
node.
– Deletion: Nodes can be deleted, and the circular structure is maintained by updating the pointers
appropriately.
– Traversal: Starts at any node and continues until the start node is encountered again, making it ideal for
scenarios where you need to loop through the list continuously.
• Advantages:
– The entire list can be traversed starting from any node.
– Useful for applications where circular traversal is needed (e.g., round-robin scheduling).
• Disadvantages:
– More complex to manage due to its circular nature, especially when inserting or deleting nodes.
– Traversal may lead to an infinite loop if not managed correctly.
• Use Case: Round-robin CPU scheduling, implementing circular buffers, and managing players in multiplayer
games.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
b. Circular Doubly Linked List

Structure: Similar to a doubly linked list, but the Next pointer of the last node points to
the first node, and the Prev pointer of the first node points to the last node, forming a
circular structure.

Head Node

A B C D

Prev Data Next

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


IMPLEMENTATION
Lists and Chains

• A List is a collection of elements, typically organized in a linear sequence.


• Unlike arrays, the elements (or nodes) in a list are not stored in contiguous
memory locations.
• Lists can grow and shrink dynamically, making them more flexible for
scenarios where the size of the collection is not fixed.
• A Chain is a specific type of list where elements (nodes) are linked together
using pointers.
• Chains are often implemented as linked lists, where each node points to
the next node in the sequence.
• Chains allow for dynamic memory allocation, meaning elements can be
added or removed without needing to shift elements like in arrays.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Operations
Insertion:
At the Beginning: The new node is added before the current head node, and the head pointer is
updated.
At the End: The new node is added after the last node, and the last node’s pointer is updated.
In the Middle: The new node is inserted between two existing nodes by updating their pointers.
Deletion:
From the Beginning: The head node is removed, and the head pointer is updated to the next node.
From the End: The last node is removed, and the second-last node’s pointer is set to NULL.
From the Middle: A node is removed by adjusting the pointers of the adjacent nodes.
Traversal:
Starting from the head node, each node is accessed sequentially until the end (or the start node
again in a circular chain) is reached.
Search:
Nodes can be searched based on specific criteria (e.g., a specific data value). The list is traversed
node by node until the target value is found.
Update:
The data field of any node can be modified directly if the node is accessible through traversal.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Representation of Chains Using C
In C programming, chains (or linked lists) are implemented using self-
referential structures. This technique allows each node of the list to contain a
pointer that refers to the next node in the sequence, effectively linking them
together.
A basic definition of a self-referential structure in C is as follows:
typedef struct list {
int data; // Data field
struct list *link; // Pointer to the next node (self-referential)
}List;

data: This field stores the data of the node (in this case, an integer).
link: This pointer of type struct Node points to another node of the same type,
making the structure self-referential.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


#include <stdio.h> // Link the nodes together
item1->link = &item2; // First node points to second
// Define a self-referential structure item2->link = &item3; // Second node points to third
item3->link = NULL; // Third node is the last, points to NULL
typedef struct list {
char data; // Data field to store a character // Traverse and print the linked list
struct list *link; // Pointer to the next node List *current = &item1;
}List; while (current != NULL) {
printf("%c -> ", current->data);
current = current->link;
int main() { }
// Create three static nodes printf("NULL\n");
List item1, item2, item3;
return 0;
// Initialize data for the nodes }
item1.data = 'a'; // First node holds 'a'
item2.data = 'b'; // Second node holds 'b'
Output:
item3.data = 'c'; // Third node holds 'c'
a -> b -> c -> NULL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


SINGLY LINKED LIST
Operations on Singly Linked List
• Insertion:
– At the Beginning: Adds a new node before the head node.
– At the End: Adds a new node after the last node of the list.
– In the Middle: Adds a node at a specific position (e.g., after a given node).
• Deletion:
– From the Beginning: Removes the head node and updates the head pointer to the next node.
– From the End: Removes the last node and updates the previous node’s pointer to NULL.
– From the Middle: Removes a node at a specific position, adjusting the pointers of adjacent nodes
accordingly.
• Traversal:
– Starts at the head node and follows the pointers to visit each node in sequence until the end
(NULL) is reached.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Defining structure

struct node
{
int data;
struct node *link;
};
typedef struct node * NODE;

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Allocating memory for node
NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct node));
if(x == NULL)
{
printf("\nInsufficient memory");
exit(0);
}
x->link = NULL;
return x;
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Insert at front
NODE insert_at_front(NODE first)
{
int val;
NODE temp;
temp = getnode();

printf("\nEnter the value: ");


scanf("%d", &val);
temp->data = val;

if(first==NULL)
return temp;

temp->link = first;
return temp;
} Structure and Applications
Data Nagaraj Bhat, SMVITM, Udupi
Insert at end
NODE insert_at_end(NODE first) /*list not empty*/
{ cur = first;
int val;
while(cur->link!=NULL)
NODE temp, cur;
temp = getnode(); {
cur = cur->link;
printf("\nEnter the value: "); }
scanf("%d", &val);
temp->data = val;
cur->link = temp;
return first;
/*List is empty*/
}
if(first==NULL)
return temp;

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Delete from front
NODE delete_at_front(NODE first) /*More than one node*/
{ temp = first;
NODE temp;
first = first->link;
/*List empty*/
if(first==NULL) temp->link=NULL;
{ printf("\nItem that got deleted is %d",
printf("\nList is empty. Cannot delete."); temp->data);
return NULL; free(temp);
} return first;
/*List having only one element*/
if(first->link ==NULL) }
{
printf("\nItem that got deleted is
%d", first->data);
free(first);
return NULL;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Delete from end
NODE delete_at_end(NODE first)
prev =NULL;
{
cur = first;
NODE cur, prev; while(cur->link!=NULL)
if(first==NULL) {
{ prev = cur;
printf("\nList is empty. Cannot delete."); cur = cur->link;
return NULL; }
} prev->link =NULL;
if(first->link ==NULL)
printf("\nItem that got deleted is %d",
{ cur->data);
printf("\nItem that got deleted is free(cur);
%d", first->data); return first;
free(first); }
return NULL;
} Structure and Applications
Data Nagaraj Bhat, SMVITM, Udupi
Display
void display(NODE first)
{
NODE cur;
cur = first;
printf("\nContents are:");
if(cur == NULL)
printf("\nList is empty. Nothing to display.");
else
{
while(cur!=NULL)
{
printf("%d ", cur->data);
cur = cur->link;
}
}
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


#include <stdio.h>
#include <stdlib.h> // Switch case to handle user's choice
// Define the structure for the node switch (choice) {
struct node { case 1:
int data; first = insert_at_front(first);
struct node *link; break;
}; case 2:
typedef struct node* NODE; first = insert_at_end(first);
// Function prototypes break;
NODE getnode(); case 3:
NODE insert_at_front(NODE first); first = delete_at_front(first);
NODE insert_at_end(NODE first); break;
NODE delete_at_front(NODE first); case 4:
NODE delete_at_end(NODE first); first = delete_at_end(first);
void display(NODE first); break;
case 5:
int main() { display(first);
NODE first = NULL; // Initialize the head pointer of the list to NULL
break;
int choice; // Variable for user choice
case 6:
exit(0);
// Menu-driven interface for the linked list operations
default:
while (1) {
printf("\nInvalid choice. Try again.\n");
printf("\n1. Insert at Front");
}
printf("\n2. Insert at End");
}
printf("\n3. Delete from Front");
printf("\n4. Delete from End");
printf("\n5. Display");
return 0;
printf("\n6. Exit");
}
printf("\nEnter your choice: ");
scanf("%d", &choice);
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
SLL
Stack
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *link;
};

typedef struct stack * NODE;


NODE top = NULL;

NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct stack));
x->link = NULL;
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


void insert_front(int item) NODE delete_front()
{ {
NODE temp;
NODE temp; if(top == NULL)
temp = getnode(); {
temp->data = item; printf("\nStack underflow");
if(top == NULL) return NULL;
}
{
else
top = temp; {
} temp = top;
else top = top->link;
{ printf("\nItem got deleted is: %d", temp->data);
free(temp);
temp->link = top; return top;
top = temp; }
} }
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
void display() void main()
{ {
NODE cur; int ch, item;
while(1)
if(top==NULL)
{
{
printf("\n~~MENU~~");
printf("\nStack is empty"); printf("\n1.Push operation");
} printf("\n2.Pop operation");
else printf("\n3.Display");
{ printf("\nEnter your choice: ");
printf("\nContents are: \n"); scanf("%d",&ch);
cur = top; switch(ch)
while(cur!=NULL) {
case 1: printf("\nEnter the item
{
to be inserted: ");
printf("| %d |\n", cur->data); scanf("%d",&item);
cur = cur->link; insert_front(item);
} break;
} case 2: top = delete_front();
} break;
case 3: display();
break;
case 4: exit(0);
}
Data Structure and Applications } Nagaraj Bhat, SMVITM, Udupi
}
SLL
Queue
#include<stdio.h>
#include<stdlib.h>
struct queue
{
int data;
struct queue *link;
};

typedef struct queue * NODE;


NODE front = NULL;
NODE rear = NULL;

NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct queue));
x->link = NULL;
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


void insert_rear(int item) NODE delete_front()
{ {
int val; NODE temp;
if(front==NULL)
NODE temp, cur;
{
temp = getnode();
printf("\nQueue underflow");
temp->data = item; return NULL;
if(front == NULL) }
{ else
front = temp; {
rear = temp; temp = front;
} front = front->link;
else printf("\nItem got deleted is: %d", temp->data);
{ free(temp);
rear->link = temp; return front;
rear = rear->link; }
} }
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


void main()
void display()
{
{ int ch, item;
NODE cur;
while(1)
if(front == NULL) {
{ printf("\n~~MENU~~");
printf("\n1.Insert operation");
printf("\nQueue is empty"); printf("\n2.Delete operation");
} printf("\n3.Display");
printf("\nEnter your choice: ");
else scanf("%d",&ch);
{ switch(ch)
printf("\nQueue contents are:\n"); {
case 1: printf("\nEnter the item to be inserted: ");
for(cur = front; cur != rear->link ; cur = cur->link) scanf("%d",&item);
printf("%d ", cur->data); insert_rear(item);
break;
} case 2: front = delete_front();
} break;
case 3: display();
break;
case 4: exit(0);
}
}
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Polynomial Addition
(Linked List)
Adding a(x) = 4x³ + 3x² + 5x + 6 and
b(x) = 5x⁴ + 4x² + 2x + 1 gives:
a(x)+b(x)= 5x⁴ + 4x³ + 7x² + 7x + 7

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Polynomial Representation Using an
Array of Structures
For sparse polynomials, an array of structures is used, where each structure contains both the
coefficient and exponent, which makes this more memory-efficient by skipping zero terms.
Structure Definition:

typedef struct {
float coeff; // Coefficient of the term
int expon; // Exponent (degree) of the term
} PolynomialTerm;

PolynomialTerm terms[MAX_TERMS]; // Array of structures


int avail = 0; // Keeps track of the next available position

Example: Multiple Polynomials


Consider two polynomials:
a(x)=15x4+24x2+12x+4
b(x)=13x3+7x+3
The memory stores only non-zero coefficients and their corresponding degrees, ignoring zero terms.
starta finisha startb finishb avail
Memory Representation terms[0] terms[1] terms[2] terms[3] terms[4] terms[5] terms[6]
Coefficient 15 24 12 4 13 7 3
Degree 4 2 1 0 3 Nagaraj1Bhat, SMVITM,
0 Udupi
Data Structure and Applications
#include<stdio.h>
#include<stdlib.h>

struct node
{ NODE
int coeff; coeff
expon
int expon;
link
struct node *link;
};
typedef struct node *NODE;

NODE getnode()
{
NODE x;
x =(NODE) malloc(sizeof(struct node));
return x;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
void main() printf("\nEnter the first polynomial \n");
{ head1 = read_poly(head1);
NODE head1,head2,head3; printf("\nEnter the second polynomial \n");
head1 = getnode(); head2 = read_poly(head2);
head2 = getnode();
head3 = poly_add(head1,head2,head3);
head3 = getnode();
printf("\nPolynomial 1:\t");
head1->link=head1; display(head1);
head2->link=head2; printf("\nPolynomial 2:\t");
head3->link=head3; display(head2);
printf("\nPolynomial Result:\t");
display(head3);
head1 head2 head3
coeff
}
expon
link &head1
Data Structure &head2
and Applications &head3 Nagaraj Bhat, SMVITM, Udupi
NODE read_poly(NODE head) NODE attach(int coeff, int expon, NODE head)
{ {
NODE temp, cur;
int i = 1, coeff, expon;
printf("\nEnter the coefficient as -999 to end the polynomial "); temp = getnode();
while(1) temp->coeff = coeff;
temp->expon = expon;
{
cur = head->link;
printf("\nEnter the %d term:\n", i++);
while(cur->link != head)
printf("\n\tCoeff = "); {
scanf("%d", &coeff); cur = cur->link;
if(coeff == -999) }
break; cur->link = temp;
Consider the polynomials:
temp->link = head;
printf("\n\tPow x = "); • a(x)=4x3+3x2+5x+6
return head;
scanf("%d", &expon); }
• b(x)=5x4+4x2+2x+1

head = attach(coeff, expon, head); a(x)+b(x)=d(x)= 5x4 +4x3 +7x2+7x+7

} head1 term1 term2 term3 term4 head2 term1 term2 term3 term4 head3

coeff 4 3 5 6 5 4 2 1
return head; }
Data Structure and Applications expon 3 2 1 0 4Nagaraj2Bhat, SMVITM,
1 0
Udupi
link term1 term2 term3 term4 head1 term1 term2 term3 term4 head2 head3
NODE poly_add(NODE head1, NODE head2, NODE head3) a
{ head1 term1 term2 term3 term4
NODE a, b;
int coeff; coeff 4 3 5 6
a = head1->link; expon 3 2 1 0
b = head2->link; link term1 term2 term3 term4 head1
while(a != head1 && b != head2)
{ b
if(a->expon == b->expon) head2 term1 term2 term3 term4
{
coeff = a->coeff + b->coeff; coeff 5 4 2 1
if(coeff != 0) expon 4 2 1 0
head3 = attach(coeff, a->expon, head3); link term1 term2 term3 term4 head2
a = a->link;
b = b->link;
} head3 term1 term2 term3 term4 term5
else if(a->expon > b->expon) coeff 5 4 7 7 7
{ expon 4 3 2 1 0
head3 = attach(a->coeff, a->expon, head3); link term1 term2 term3 term4 terrm5 head3
a = a->link;
}
else Consider the polynomials:
{
head3 = attach(b->coeff, b->expon, head3); • a(x)=4x3+3x2+5x+6
b = b->link; • b(x)=5x4+4x2+2x+1
}
}//end Data Structure and Applications
while a(x)+b(x)=d(x)= 5x4 +4x 3 +7x2+7x+7
Nagaraj Bhat, SMVITM, Udupi
while(a != head1)
{
head3 = attach(a->coeff, a->expon, head3);
a = a->link;
}
while(b != head2)
{
head3 = attach(b->coeff, b->expon, head3);
b = b->link;
}
return head3;
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


void display(NODE head)
{
NODE temp;
if(head->link == head)
{
printf("\nPolynomial does not exist");
return;
}
temp = head->link;
while(temp != head)
{
printf("%d x^%d",temp->coeff, temp->expon);
temp = temp->link;
if(temp != head)
printf(" + ");
}
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Develop a menu driven Program in C for the following operations on Singly
LinkedList(SLL) of student Data with the fields: USN, Name, Programme, Sem,
PhNo.
a. Create a SLL of N Students Data by using frontinsertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion/Deletion at End of SLL
d. Perform Insertion/Deletion at Front of SLL(Demonstration of stack)
e. Exit

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


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

// Structure to store student data


struct node {
char usn[25], name[25], branch[25]; // Fields for student data: USN, Name,
Branch
int sem; // Semester of the student
long int phone; // Phone number of the student
struct node *link; // Pointer to the next node in the linked list
};

typedef struct node * NODE; // Define NODE as a pointer to struct node


NODE start = NULL; // Initialize start pointer to NULL (beginning of the list)
int count = 0; // Counter to keep track of the number of nodes
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
// Function to create a new node and input student data
NODE create() {
NODE snode;
snode = (NODE)malloc(sizeof(struct node)); // Allocate memory for a new node
if (snode == NULL) {
printf("\nMemory is not available"); // Check for memory allocation failure
exit(1);
}
// Input student details
printf("\nEnter the USN, Name, Branch, Semester, and Phone Number of the student: ");
scanf("%s %s %s %d %ld", snode->usn, snode->name, snode->branch, &snode->sem,
&snode->phone);
snode->link = NULL; // Set the link of the new node to NULL
count++; // Increment the count of nodes
return snode; // Return the newly created node
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
// Function to insert a node at the front of the SLL
NODE insertfront() {
NODE temp = create(); // Create a new node with student data
if (start == NULL) { // If the list is empty, the new node becomes the
start
return temp;
}
temp->link = start; // Link the new node to the current start node
return temp; // Return the new node as the start
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to delete a node from the front of the SLL
NODE deletefront() {
NODE temp;
if (start == NULL) { // Check if the list is empty
printf("\nLinked list is empty");
return NULL;
}
temp = start; // Store the current start node in a temp variable
start = start->link; // Update the start to the next node in the list
printf("\nThe Student node with USN: %s is deleted", temp->usn); // Print
details of deleted node
free(temp); // Free the memory of the deleted node
count--; // Decrement the node count
return start; // Return the new start of the list
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to delete a node from the end of the SLL
NODE deleteend() {
NODE cur, prev;
if (start == NULL) { // Check if the list is empty
printf("\nLinked List is empty");
return NULL;
}
if (start->link == NULL) { // If there is only one node in the list
printf("\nThe student node with USN: %s is deleted", start->usn);
free(start); // Delete the single node
count--;
return NULL; // Set start to NULL as the list is now empty
}
prev = NULL;
cur = start;
while (cur->link != NULL) { // Traverse to the last node
prev = cur;
cur = cur->link;
}
printf("\nThe student node with USN: %s is deleted", cur->usn); // Print details of deleted node
free(cur); // Free the memory of the last node
prev->link = NULL; // Update the previous node's link to NULL (new end of the list)
count--; // Decrement the node count
return start; // Return the start of the list
} Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
// Function to display the SLL
void display() {
NODE cur;
int num = 1;
if (start == NULL) { // Check if the list is empty
printf("\nNo Contents to display in SLL\n");
return;
}
printf("\nThe contents of SLL:\n");
cur = start;
while (cur != NULL) { // Traverse the list and print each node's details
printf("\n||%d|| USN: %s | Name: %s | Branch: %s | Sem: %d | Ph: %ld |",
num, cur->usn, cur->name, cur->branch, cur->sem, cur->phone);
cur = cur->link; // Move to the next node
num++;
}
printf("\nNumber of student nodes: %d\n", count); // Print the total number of nodes
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to demonstrate stack operations using SLL (front insertion and deletion)
void stackdemo() {
int ch;
while (1) {
printf("\n~~~ Stack Demo using SLL ~~~\n");
printf("\n1: Push operation\n2: Pop operation\n3: Display\n4: Exit\n");
printf("\nEnter your choice for stack demo: ");
scanf("%d", &ch);
switch (ch) {
case 1: start = insertfront(); // Stack Push operation (insert at front)
break;
case 2: start = deletefront(); // Stack Pop operation (delete from front)
break;
case 3: display(); // Display the current stack (SLL)
break;
default: return; // Exit the stack demo
}
}
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Main function to handle all menu-driven SLL operations
int main() { switch (ch) {
int ch, i, n; case 1: // Create SLL of N student nodes using front insertion
while (1) { printf("\nEnter the number of students: ");
printf("\n~~~ Menu ~~~"); scanf("%d", &n);
for (i = 1; i <= n; i++)
printf("\nEnter your choice for SLL operation: "); start = insertfront();
printf("\n1: Create SLL of Student Nodes"); break;
printf("\n2: Display Status"); case 2: // Display the SLL
printf("\n3: Insert at End"); display();
printf("\n4: Delete at End"); break;
case 3: // Insert at the end of SLL
printf("\n5: Stack Demo using SLL start = insertend();
(Insertion and Deletion at Front)"); break;
printf("\n6: Exit\n"); case 4: // Delete the last node in the SLL
printf("\nEnter your choice: "); start = deleteend();
scanf("%d", &ch); break;
case 5: // Stack demonstration with front insertion/deletion
stackdemo();
break;
case 6: // Exit the program
exit(0);
default: // Handle invalid menu input
printf("\nPlease enter a valid choice");
}
Data Structure and Applications } Nagaraj Bhat, SMVITM, Udupi
}
SLL
Queue
MODULE 3:
Advanced Linked Lists and Trees

• Additional List Operations, Sparse Matrices, Doubly Linked List


• Trees, Introduction to Binary Trees, Binary Tree Traversals, Threaded
Binary Trees

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Additional List Operations

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Insert at position
NODE insert_at_pos(NODE first) prev = NULL;
{ cur = first;
int val,pos,i;
NODE temp, cur, prev; for(i =1; cur != NULL && i<pos; i++)
temp = getnode(); {
prev = cur;
printf("\nEnter the value to be inserted: "); cur = cur->link;
scanf("%d",&val); }
temp->data = val; if(cur==NULL)
{
if(first==NULL) printf("\nThere are less than %d elements", pos);
return temp; return first;
printf("\nEnter the position where node }
to inserted:");
else
scanf("%d",&pos);
{
if(pos==1)
prev->link = temp;
{ temp->link = cur;
temp->link = first; return first;
return temp; }
} }
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Search
void search(NODE first) cur = first;
{ while(cur!=NULL)
int key,flag=0; {
NODE cur; if(cur->data == key)
if(first == NULL) { flag=1;
{ break;
printf("\nList is empty"); }
return; cur = cur->link;
} }
printf("\nEnter the item to be searched: "); if(flag == 0)
scanf("%d", &key); printf("\nUnsuccessful search");
else
printf("\nSuccessful search");
Data Structure and Applications } Nagaraj Bhat, SMVITM, Udupi
Count number of nodes
void countnode(NODE first)
{
NODE cur;
int count=0;
cur = first;
while(cur!=NULL)
{
count++;
cur= cur->link;
}
printf("\nTotal number of nodes are: %d", count);
} and Applications
Data Structure Nagaraj Bhat, SMVITM, Udupi
Identifying Biggest Node
NODE largest_node(NODE first)
{
NODE cur, large;
int largest=0;
cur = first;
while(cur!=NULL)
{
if(cur->data>large)
{
largest= cur->data ;
large=cur;
}
cur= cur->link;
}
printf("\nlargest value: %d", largest);
return large;
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
}
Concatenate two lists
NODE concat(NODE first, NODE second)
{
NODE cur;
if(first==NULL)
return second;
if(second==NULL)
return first;
cur = first;
while(cur->link!=NULL)
{
cur = cur->link;
}
cur->link = second;
return first;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Reverse list
NODE reverse(NODE first)
{
NODE rev, temp;
if(first==NULL)
{
printf("\nList empty");
return NULL;
}
rev =NULL;
while(first!=NULL)
{
temp = first;
first = first->link;
temp->link = rev;
rev = temp;
}
return rev;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Ordered list
NODE insert_order(NODE first)
{ prev = NULL;
int item; cur = first;
NODE temp, cur, prev; while(cur!=NULL && item >= cur->data)
temp = getnode(); {
prev = cur;
printf("\nEnter the value: "); cur = cur->link;
scanf("%d", &item); }
temp->data = item;
if(first==NULL)
return temp; prev->link = temp;
if(item < first->data) temp->link = cur;
{ return first;
temp->link = first; }
return temp;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Doubly Linked List

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Doubly Linked List
• Structure: In a doubly linked list, each node contains:
o Data: The value or information of the node.
o Prev: A pointer that points to the previous node.
o Next: A pointer that points to the next node in the sequence.
• Connection: The nodes are connected in both forward and backward directions, allowing for
traversal in either direction. The first node’s Prev pointer is set to NULL, and the last node’s Next
pointer is also set to NULL.

Head Node

NULL A B C D NULL

Prev Data Next


Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Structure Definition

struct node
{
int data;
struct node *llink;
struct node *rlink;
};
typedef struct node* NODE;

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Memory allocation
NODE getnode()
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nInsufficient memory");
exit(0);
}
x->llink=NULL;
x->rlink=NULL;
return x;
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
NODE insert_at_end(NODE first)
NODE insert_at_front(NODE first)
{
{ int val;
int val; NODE cur, temp;
NODE temp; temp = getnode();
temp = getnode(); printf("\nEnter the value to be inserted: ");
scanf("%d",&val);
printf("\nEnter the value to be inserted: ");
temp->data = val;
scanf("%d",&val);
temp->data = val; if(first == NULL)
if(first == NULL) {
{ return temp;
}
return temp;
cur= first;
} while(cur->rlink != NULL)
temp->rlink = first; {
first->llink = temp; cur = cur->rlink;
return temp; }
}
cur->rlink = temp;
temp->llink = cur;
return first;
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
}
NODE insert_at_pos(NODE first) prev = NULL;
{ cur = first;
int val,pos,i; for(i =1; cur != NULL && i<pos; i++)
NODE temp, cur, prev; {
temp = getnode(); prev = cur;
printf("\nEnter the value to be inserted: "); cur = cur->rlink;
}
scanf("%d",&val);
if(cur==NULL)
temp->data = val; {
if(first==NULL) printf("\nThere are less than %d elements", pos);
return temp; return first;
}
printf("\nEnter the position where node to inserted:"); else
scanf("%d",&pos); {
if(pos==1) prev->rlink = temp;
{ temp->llink = prev;
temp->rlink = first; temp->rlink = cur;
cur->llink=temp;
first->llink =temp;
return first;
return temp; }
} }

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


NODE delete_at_end(NODE first)
NODE delete_at_front(NODE first) {
{ NODE prev,cur;
NODE temp; if(first == NULL)
{
if(first == NULL) printf("\nDoubly Linked List is empty");
{ return NULL;
printf("\nDoubly Linked List is empty"); }
return NULL; if(first->rlink == NULL)
{
}
printf("\nThe node %d is deleted", first->data);
if(first->rlink== NULL) free(first);
{ return NULL;
printf("\nThe node %d is deleted",first->data); }
free(first); prev=NULL;
cur=first;
return NULL;
while(cur->rlink!=NULL)
} {
temp = first; prev=cur;
first = first->rlink; cur = cur->rlink;
temp->rlink = NULL; }
cur->llink = NULL;
first->llink = NULL;
prev->rlink = NULL;
printf("\nThe node %d is deleted", temp->data); printf("\nThe node %d is deleted",cur->data);
free(temp); free(cur);
return first; return first;
} Data Structure and Applications } Nagaraj Bhat, SMVITM, Udupi
NODE delete_at_midle(NODE first) else
{ {
int val, key; cur = first;
while(cur != NULL)
NODE prev, cur;
{
prev =NULL; if( cur->data == key)
break;
if(first==NULL) prev = cur;
{ cur = cur->rlink;
}
printf("\nList empty cannot delete");
if(cur==NULL)
return NULL; {
} printf("\nKey element not found");
printf("\nEnter the key:"); return first;
scanf("%d", &key); }
if(cur->rlink==NULL)
{
if(first->rlink==NULL && first->data == key) prev->rlink=NULL;
{ }
printf("\nItem that got deleted is %d", first->data); else
free(first); {
prev->rlink = cur->rlink;
return NULL;
cur->rlink->llink = prev;
} }
printf("\nItem that got deleted is %d", cur->data);
free(cur);
return first;
}
Data Structure and Applications } Nagaraj Bhat, SMVITM, Udupi
void display(NODE first)
{
NODE cur;
cur = first;
printf("\nContents are:");
if(cur == NULL)
printf("\nList is empty. Nothing to display.");
else
{
while(cur!=NULL)
{
printf("%d ", cur->data);
cur = cur->rlink;
}
}
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


#include <stdio.h>
#include <stdlib.h> // Switch case to handle user's choice
// Define the structure for the node switch (choice) {
struct node { case 1:
int data;
first = insert_at_front(first);
struct node *link;
break;
struct node *rink;
};
case 2:
typedef struct node* NODE; first = insert_at_end(first);
// Function prototypes break;
NODE getnode(); case 3:
NODE insert_at_front(NODE first); first = insert_at_pos(first);
NODE insert_at_end(NODE first); break;
NODE insert_at_pos(NODE first); case 4:
NODE delete_at_front(NODE first); first = delete_at_front(first);
NODE delete_at_end(NODE first); break;
void display(NODE first);
case 5:
first = delete_at_end(first);
int main() {
NODE first = NULL; // Initialize the head pointer of the list to NULL
break;
int choice; // Variable for user choice case 6:
display(first);
// Menu-driven interface for the linked list operations break;
while (1) { case 7:
printf("\n1. Insert at Front"); exit(0);
printf("\n2. Insert at End"); default:
printf("\n3. Insert at Position"); printf("\nInvalid choice. Try again.\n");
printf("\n4. Delete from Front"); }
printf("\n5. Delete from End");
}
printf("\n6. Display");
printf("\n7. Exit");
printf("\nEnter your and
choice: ");
return 0;
Data Structure Applications } Nagaraj Bhat, SMVITM, Udupi
scanf("%d", &choice);
Develop a menu driven Program in C for the following operations on Doubly
Linked List(DLL) of Employee Data with the fields:
SSN,Name,Dept,Designation, Sal, PhNo.

a. Create a DLL of N Employees Data by using end insertion.


b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate How this DLL can be used as a Double Ended Queue.
f. Exit.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


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

// Define the structure for a node in the doubly linked list


struct node {
char ssn[25], name[25], dept[10], designation[25]; // Employee details
int sal; // Salary of the employee
long int phone; // Phone number of the employee
struct node *llink; // Pointer to the previous node
struct node *rlink; // Pointer to the next node
};

typedef struct node * NODE; // Define NODE as a pointer to struct node


NODE first = NULL; // Initialize the start (first) of the DLL to NULL
int count = 0; // Counter to track the number of nodes in the DLL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to create a new node with employee data
NODE create() {
NODE enode;
enode = (NODE)malloc(sizeof(struct node)); // Allocate memory for the new node
if (enode == NULL) {
printf("\nRunning out of memory"); // Check for memory allocation failure
exit(0);
}
// Input employee details
printf("\nEnter the SSN, Name, Department, Designation, Salary, and Phone Number of the employee:
\n");
scanf("%s %s %s %s %d %ld", enode->ssn, enode->name, enode->dept, enode->designation, &enode-
>sal, &enode->phone);
enode->llink = NULL; // Set the left link to NULL
enode->rlink = NULL; // Set the right link to NULL
count++; // Increment the node count
return enode; // Return the newly created node
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to insert a node at the front of the DLL
NODE insertfront() {
NODE temp = create(); // Create a new node
if (first == NULL) { // If the list is empty, the new node becomes the start
return temp;
}
temp->rlink = first; // Link the new node's right link to the current first node
first->llink = temp; // Set the current first node's left link to the new node
return temp; // Return the new node as the start of the list
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to insert a node at the end of the DLL
NODE insertend() {
NODE cur, temp = create(); // Create a new node
if (first == NULL) { // If the list is empty, the new node becomes the start
return temp;
}
cur = first;
while (cur->rlink != NULL) { // Traverse to the last node of the list
cur = cur->rlink;
}
cur->rlink = temp; // Link the last node's right link to the new node
temp->llink = cur; // Link the new node's left link to the last node
return first; // Return the start of the list
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to delete a node from the front of the DLL
NODE deletefront() {
NODE temp;
if (first == NULL) { // Check if the list is empty
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first->rlink == NULL) { // If there's only one node in the list
printf("\nThe employee node with SSN: %s is deleted", first->ssn);
free(first); // Free the single node
count--;
return NULL; // Set first to NULL as the list is now empty
}
temp = first; // Store the current first node in temp
first = first->rlink; // Move first to the second node in the list
temp->rlink = NULL;
first->llink = NULL; // Set the new first node's left link to NULL
printf("\nThe employee node with SSN: %s is deleted", temp->ssn);
free(temp); // Free the old first node
count--;
return first; // Return the new start of the list
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to delete a node from the end of the DLL
NODE deleteend() {
NODE prev, cur;
if (first == NULL) { // Check if the list is empty
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first->rlink == NULL) { // If there's only one node in the list
printf("\nThe employee node with SSN: %s is deleted", first->ssn);
free(first); // Free the single node
count--;
return NULL;
}
prev = NULL;
cur = first;
while (cur->rlink != NULL) { // Traverse to the last node
prev = cur;
cur = cur->rlink;
}
printf("\nThe employee node with SSN: %s is deleted", cur->ssn);
free(cur); // Free the last node
prev->rlink = NULL; // Set the second last node's right link to NULL
count--;
return first; // Return the start of the list
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
// Function to display all nodes in the DLL
void display() {
NODE cur;
int nodeno = 1;
cur = first; // Start from the first node
if (cur == NULL) {
printf("\nNo Contents to display in DLL"); // Check if the list is empty
return;
}
printf("\nThe contents of DLL:\n");
while (cur != NULL) { // Traverse the list and display each node's data
printf("\nENode:%d || SSN:%s | Name:%s | Department:%s | Designation:%s | Salary:%d | Phone
no:%ld",
nodeno, cur->ssn, cur->name, cur->dept, cur->designation, cur->sal, cur->phone);
cur = cur->rlink; // Move to the next node
nodeno++;
}
printf("\nNumber of employee nodes: %d", count); // Display the total count of nodes
}

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


// Function to demonstrate double-ended queue (DEQ) operations using DLL
void deqdemo() {
int ch;
while (1) {
printf("\nDemo Double Ended Queue Operations:");
printf("\n1: Insert at Queue Front\n2: Delete from Queue Front\n3: Insert at Queue Rear\n4: Delete from
Queue Rear\n5: Display DLL\n6: Exit\n");
scanf("%d", &ch);
switch (ch) {
case 1: first = insertfront(); // Insert at the front (DEQ front insertion)
break;
case 2: first = deletefront(); // Delete from the front (DEQ front deletion)
break;
case 3: first = insertend(); // Insert at the end (DEQ rear insertion)
break;
case 4: first = deleteend(); // Delete from the end (DEQ rear deletion)
break;
case 5: display(); // Display the list
break;
default: return; // Exit the DEQ demo
}
}
}
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
// Main function for menu-driven DLL operations case 2: // Display all nodes in DLL
void main() { display();
int ch, i, n; break;
case 3: // Insert node at end
while (1) {
first = insertend();
printf("\n\n~~~ Menu ~~~");
break;
printf("\n1: Create DLL of Employee Nodes");
case 4: // Delete node from end
printf("\n2: Display DLL");
first = deleteend();
printf("\n3: Insert at End");
break;
printf("\n4: Delete at End");
case 5: // Insert node at front
printf("\n5: Insert at Front");
first = insertfront();
printf("\n6: Delete at Front");
break;
printf("\n7: Double Ended Queue Demo using DLL");
case 6: // Delete node from front
printf("\n8: Exit\n");
first = deletefront();
printf("\nPlease enter your choice: ");
break;
scanf("%d", &ch);
case 7: // Demonstrate double-ended queue operations
switch (ch) { deqdemo();
case 1: // Create DLL with N employee nodes using end break;
insertion
case 8: // Exit the program
printf("\nEnter the number of employees: "); exit(0);
scanf("%d", &n); default:
for (i = 1; i <= n; i++) printf("\nPlease enter a valid choice");
first = insertend(); } }
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
break; }
Sparse Matrices Representation
Using Doubly Linked List

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Sparse Matrix Storage

Sparse Matrix: An array of triples

a a Row Column Value


0 0 0 0 0 8 [0] 6 6 6
0 1 0 0 0 0 [1] 0 5 8
0 0 6 0 0 0 [2] 1 1 1
0 0 0 0 0 0 [3] 2 2 6
0 2 0 0 4 0 [4] 4 1 2
0 0 3 0 0 0 [5] 4 4 4
[6] 5 2 3

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


• Each column of a spars matrix represented as a circular linked list with a header
node having three fields: next, down and right.
head next: header of the next element
next
right: not used
down right down: points to next element in the column

• Each column of a spars matrix represented as a circular linked list with a header
node having three fields: next, down and right.
head next: not used
next
right: points to next element in the row
down right down: not used

• Each item represented as a node having five fields: row, col, val, down, right.

head right: points to next element in the row


row col val
down: points to next element in the column
down right

• First node in the below list diagram is identified as variable head which contains
size of the matrix (No. of Columns, No of Rows and No of Non Zero Values)
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
0 1 2 3 4 5
6 6 6 next next next next next next
down right down right down right down right down right down right down right

next 0 5 8
0 down right down right

next 1 1 1
1
down right down right

next 2 2 6
2
down right down right

next
3 down right

next 4 1 2 4 4 4
4
down right down right down right

next 5 2 3
5
down right down right

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A tree is a hierarchical data structure composed of nodes, where each node
represents an element and is connected to other nodes via edges.
where:
• One node is designated as the root.
• Each node (except the root) has exactly one parent.
• A node can have zero or more children.
• A tree structure does not contain any cycles, making it a type of acyclic
connected graph.
A

Data Structure and Applications E X F Nagaraj Bhat, SMVITM, Udupi


Tree Terminology

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Node: A basic unit of a tree that contains data and may have links to other nodes.
• Each element in a tree is a node. It may or may not have children. Nodes are the
building blocks of trees.

Node
A

Node

Node E Node F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Root: The topmost node of a tree, which has no parent.
• The root is the starting point of the tree.
• Every tree has only one root.
• In this example, A is the root node.

Node
A Root

Node

Node E Node F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Edge: A connection between two nodes.
• An edge represents a link between two nodes.
• The connections between A and B, A and C, B and D, B and F, C and F are
edges. The edges are the lines that connect the nodes.

Edge

Edge Edge
E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Parent and Child
• Parent: A node with at least one child.
• Child: A node that descends from another node.
• A is the parent of B and C. B and C are children of A

Parent
A

Children

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Siblings: Nodes that share the same parent.
• B and C are siblings because they have the same parent (A).
• D and E are siblings because they have the same parent (B).

Parent
A

Siblings

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Leaf: A node that has no children.
• D, E and F are leaf nodes because they do not have any children.

Leaf E Leaf F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Internal Node: A node that has at least one child; not a leaf node.
• A, B and C are internal nodes because they have children.

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Ancestors: All the nodes along the path from the root to a specific node, excluding
the node itself.
• The ancestors of node E are A and B.
• The ancestors of node D are A and B.
• The ancestors of node F are A and C.

Ancestors ? E F
Ancestors ?

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Descendants: All nodes that fall under a given node, including children,
grandchildren, etc.
• The descendants of node B are D and E.
• The descendants of node A are B, C, D, E and F.

Descendants

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Left Descendants
• A left descendant of a node is any node that can be reached by following the left
child links starting from that node.
• Left descendants of A: B and D.
• Left descendants of B: D.

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Right Descendants
• A right descendant is any node that can be reached by following the right child
links starting from that node.
• Right descendants of A: C, and F.
• Right descendant of B: E

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Path: A sequence of nodes and edges connecting a node to another node.
• The path from A to E is A -> B -> E.

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Subtree: A smaller tree within a larger tree that includes a node and all its
descendants.
• The subtree rooted at B includes B, D, and E

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Left and Right Subtrees
• The left subtree of a node is the subtree that starts at the left child of that node and
includes all of its descendants.

• The right subtree of a node is the subtree that starts at the right child of that node and
includes all of its descendants.

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Height of the Tree: The number of edges from the root to the deepest leaf node.

• The height of this tree is 2 (from A to D/E).

A
1

E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Depth of a Node: The number of edges from the root node to the specific node.
• The depth of node E is 2 (edges from A to B to E).
• The depth of node B is ?1

A
1

2
E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Level: Distance of a node from the root node is called as level of the node.
• A is at level 0, B and C are at level 1, and D and E are at level 2.

Level 1 A

Level 2

Level 3 E F F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Summary of the Terminologies with Examples
Node: A fundamental unit in the tree (A, B, C).
Root: The topmost node (A).
Edge: The connections between nodes (A-B, A-C).
Parent and Child: A is the parent of B and C; B is the parent of D and E.
Siblings: B and C; D and E.
Leaf: Nodes without children (D, E, C if no further connections).
Internal Node: A, B (nodes with children).
A
Ancestors: A and B are ancestors of E.
Descendants: D and E are descendants of B.
Path: From A to E is A -> B -> E.
Subtree: A tree rooted at B is B -> D, E.
Height: The longest path from the root to a leaf (2 in this case).
Depth: E has a depth of 2.
Level: A is at level 0, B and C at level 1, and D and E at level 2. E F

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Representation of Trees

• List Representation
• Left Child and Right Sibling Representation
• Left Child-Right Child Representation

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


List Representation
• The root node comes first
• It is immediately followed by list of its subtree from left.
• Head nodes represents parent nodes and it contains two link section.
• Head Node connects to its children.
• This is recursively repeated for each subtree.

B C

E F G H I J
1st Child 2nd Child 3rd Child

A NULL

1st child 2nd child 1st child 1st child 2nd child 3rd child

B E F NULL C G NULL D H I J NULL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A
List Representation

B C

E F G H I J

K L

1st Child 2nd Child 3rd Child

A NULL

1st child 2nd child 1st child 1st child 2nd child 3rd child

B F NULL C G NULL D H I J NULL

1st child 2nd child


E K L NULL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A
List Representation

B C

E F G H I

K L

1st Child 2nd Child 3rd Child

A C NULL

1st child 2nd child 1st child 2nd child 3rd child

B F NULL D H I J NULL

1st child 2nd child


E K L NULL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Left Child and Right Sibling Representation

Left child node of every parent is connected to its siblings

A A

B C B C

E F G H I J E F G H I J

K L K L

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Left Child and Right Sibling Representation

Left child node of every parent is connected to its siblings


A A

B C B C

E F G H I J E F G G H I

K L M N O K L M N O

P Q
Data Structure and Applications P Q Nagaraj Bhat, SMVITM, Udupi
Left Child-Right Child Representation
(Binary Tree)

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A A

B C B C

E F G H I J E F G H I J

K L M K L M

45o

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


A A

B C B C

E F G H I J E F G H I J

K L K L Left Child and Right Sibling Representation

Left Child-Right
Data Structure Child Representation
and Applications Nagaraj Bhat, SMVITM, Udupi
(Binary Tree)
Binary Tree

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Binary Tree

• A binary tree is a collection of nodes that


consists of the root and other subsets to the A
root points, which are called the left and right
subtrees.

• Every parent node on a binary tree can have up


to two child nodes (roots of the two subtrees);
any more children and it becomes a general
tree. E F

• A node that has no children is called a leaf


node.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Types of Binary Tree
1. Strictly Binary Tree: In a 2. Skewed Binary Tree: A binary 3. Complete Binary Tree: A binary
strictly binary tree, each tree where all nodes have only tree in which all levels are
non-leaf node has exactly one child, either left or right, completely filled except possibly
two children. forming a single path. the last level, and the nodes are
as far left as possible.

A A A A

E F F F E F
Types of Binary Tree
4. Expression Tree: A binary tree used to 5. Binary Search Tree (BST): A binary tree in which each
represent arithmetic expressions. Internal node’s left child contains values less than the node, and
nodes represent operators, and leaf nodes the right child contains values greater than the node.
represent operands.
In an expression tree, nodes represent
operands (like 3, 4, 5) or operators (like +, *).
This tree represents the expression (3 + 4) * 5.

* 5

4 4 7 9
Properties of the Binary Tree
Property 1: Maximum Number of Nodes at Any Level
Statement: The maximum number of nodes at any level i of a binary
tree is 2i−1, where i represents the level.

Proof
• At level 1 (the root level), there is 1 node: 21−1=20=1.
• At level 2, each node at level 1 can have two children, so there
are 2 nodes: 22−1=21=2.
• At level 3, each node at level 2 can also have two children, so
there are 4 nodes: 23−1=22=4.
• This pattern continues such that at any level i, the maximum
number of nodes is 2i−1.

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Proof by Induction Using the Suggested Approach
Step 1: Base Case
For the base case, we consider level i=1.
At level i=1 (the root level), there is exactly 1 node.
According to our formula, the maximum number of nodes at level i=1 should be 21−1=20=1.
This matches the actual number of nodes, so the base case holds.

Step 2: Inductive Hypothesis


Now we assume that the formula holds for level i−1:
The maximum number of nodes at level i−1 is 2i−2.
Example: i=3 then i-1= 2(level)=2i−2=23−2=2

Step 3: Prove for Level i


To prove the formula holds for level i, let’s calculate the maximum number of nodes at level i based on the
maximum nodes at level i−1.
Number of Nodes at Level i−1:
According to our inductive hypothesis, the maximum number of nodes at level i−1 is 2i−2.
Calculating Maximum Nodes at Level i:
In a binary tree, each node can have a maximum of 2 children.
Therefore, if there are 2i−2 nodes at level i−1, then the maximum number of nodes at level i will be twice that,
or:2× 2i−2 =21× 2i−2=2i−1
Conclusion:
We have shown that if the maximum number of nodes at level i−1 is 2i−2, then the maximum number of nodes at
level i is 2i−1.
Data Structure and
Therefore, the maximum number of nodes at level i in a binary tree is 2i−1 for Nagaraj
Applications
by induction, Bhat,
any level i. SMVITM, Udupi
Property 2: Maximum Number of Nodes in a Binary Tree of Depth k
Statement: The maximum number of nodes in a binary tree
of depth k is , where k represents the depth of
the tree (or the number of levels). i=1

Proof
• To find the maximum number of nodes in a binary tree of
depth k, we add up the maximum number of nodes at i=K
each level from i=1 to i=k.
• From Property 1, we know that the maximum number of For a binary tree of depth k=3:
nodes at level i is 2i−1.
• Therefore, the total maximum number of nodes up to
So, the maximum number of nodes in a
depth k is: binary tree of depth 3 is 23−1=7.

• This is a geometric series with the sum:


• Thus, the maximum number of nodes in a binary tree of
depth k is 2k−1.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Property 3: Maximum Number of Leaf Node in a Binary Tree
Step1: Define the Relationship Between Nodes and Edges Number of Leaf node of the tree=n0=n2+1
• In a binary tree: where:
– Each leaf node n0 has 0 edges (no children).
– Each node with one child n1 has 1 edge. n0​: Number of leaf nodes (nodes with 0 children).
– Each node with two children n2 has 2 edges. n1​: Number of nodes with 1 child.
• Therefore, we can write the total number of edges B as: n2​: Number of nodes with 2 children.
B=(n0 ×0)+(n1×1)+(n2×2) Simplifying, we get: B= n1+2 × n2 →1 nn: Total number of nodes in the binary tree.
B: Total number of edges in the binary tree.
Step2: Relate Total Nodes n to Edges B
• In a binary tree, the total number of nodes n can be expressed in terms of leaf and internal nodes: n= n0 + n1+ n2 →2
• ​Since in a connected binary tree, the total number of edges B is always one less than the number of nodes B=n−1 →3

Step3: Substitute equation 3 in 1 the Expression for B


n−1 = n1+2 × n2 →4

Step4: Substitute equation 2 into the Equation 4


n0 + n1+ n2 −1 =n1+2 × n2
Step5: Simplify the Equation

n0 −1 = n2
n0Data
=​n2Structure
+1 and Applications Nagaraj Bhat, SMVITM, Udupi
Binary Tree Representation

• Array Representation
• List Representation

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


1 A
Array Representation
In an array representation of a binary tree, the tree
2 B 3 nodes are stored in a single-dimensional array rather than
using linked structures.

1.Root Node:
4 D 5 E 6 F •The root node of the tree is stored at the first index of
the array, typically at index 1.
A B C D E F
0 1 2 3 4 5 6 2.Indexing Formula:
For a node at position i in the array:
Index Node Explanation •The left child of the node is stored at index 2 * i.
1 A Root node •The right child of the node is stored at index 2 * i + 1.
2 B Left child of A (2 * 1)

3 C Right child of A (2 * 1 + 1)

4 D Left child of B (2 * 2)

5 E Right child of B (2 * 2 + 1)
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
6 F Left child of C (2 * 3 )
1 A
Array Representation
In an array representation of a binary tree, the tree
nodes are stored in a single-dimensional array rather
2 B 3
than using linked structures.

1.Root Node:
4 D 5 E 7 F •The root node of the tree is stored at the first index
of the array, typically at index 1.
A B C D E F
2.Indexing Formula:
0 1 2 3 4 5 6 7 For a node at position i in the array:
•The left child of the node is stored at index 2 * i.
Index Node Explanation
•The right child of the node is stored at index 2 * i
1 A Root node
+ 1.
2 B Left child of A (2 * 1)

3 C Right child of A (2 * 1 + 1)

4 D Left child of B (2 * 2)

5 E Right child of B (2 * 2 + 1)
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
7 F Right child of C (2 * 3 + 1)
List Representation
A
In the list representation of a binary tree, each node of the
tree is represented by the list node. Each node contains
B three main parts:
1.Data: The value or data stored in the node.
2.Left Pointer: A pointer to the left child of the node.
E 3.Right Pointer: A pointer to the right child of the node.
D F G The leaf nodes links points to NULL

H I
A

B NULL E NULL C NULL G NULL

NULL H NULL D NULL I NULL


NULL F NULL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


TREE TRAVERASAL

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversal

Tree traversal is a process of visiting each node in a tree data


structure, exactly once, to perform some operation.
There are three common ways to traverse a tree:
–Inorder: Traverse the left subtree (in order), visit the root and the
traverse the right subtree (in order).
–Preorder: Visit the root, traverse the left subtree (preorder) and
then traverse the right subtree (preorder)
–Postorder: Traverse the left subtree (postorder), traverse the right
subtree (postorder) and then visit the root.
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
1. Inorder Traversal
• Definition: In Inorder traversal, the A
nodes are visited in the following order:
– Traverse the left subtree.
– Visit the root node.
– Traverse the right subtree.
• Pattern: Left -> Root -> Right E
DB E A C
A A A A A

E
Data Structure and Applications E E E E
Nagaraj Bhat, SMVITM, Udupi
Inorder C Function • Starting at the Root (A):


The function is initially called with root = A.
Check if A is NULL: A is not NULL, so the function proceeds.
– It first recursively calls inorder(A->left), moving to B.
#include <stdio.h> • At Node B:
– The function is now at B.
– Check if B is NULL: B is not NULL, so the function proceeds.
– It then calls inorder(B->left), moving to D.
struct Node { • At Node D:
char data; –

The function is now at D.
Check if D is NULL: D is not NULL, so the function proceeds.
struct Node *left; –

D has no left child, so inorder(D->left) is called and immediately returns since D->left is NULL.
Visit D: D is printed. Output so far: D
struct Node *right; – The function calls inorder(D->right), which immediately returns because D->right is NULL.
• Back to Node B:
}; – After finishing the left subtree of B, the function returns to B.
– Visit B: B is printed. Output so far: D B
struct Node *root = NULL; – The function then calls inorder(B->right), moving to E.
• At Node E:
void inorder( Node root) { – The function is now at E.
– Check if E is NULL: E is not NULL, so the function proceeds.
if (root == NULL) return; – E has no left child, so inorder(E->left) returns immediately since E->left is NULL.

inorder(root->left); –
Visit E: E is printed. Output so far: D B E
The function calls inorder(E->right), which returns immediately because E->right is NULL.
printf("%c ", root->data); • Back to Node A:
– After finishing the left subtree of A, the function returns to A.
inorder(root->right); –

Visit A: A is printed. Output so far: D B E A
The function calls inorder(A->right), moving to C.
} • At Node C:
– The function is now at C.
– Check if C is NULL: C is not NULL, so the function proceeds.
– C has no left child, so inorder(C->left) returns immediately since C->left is NULL.
– Visit C: C is printed. Output so far: D B E A C
– The function calls inorder(C->right), which returns immediately because C->right is NULL.
– The final output of the inorder traversal for the given tree is: D B E A C

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


2. Preorder Traversal
• Definition: In Preorder traversal, the A
nodes are visited in the following order:
– Visit the root node.
– Traverse the left subtree.
– Traverse the right subtree.
• Pattern: Root -> Left -> Right E
ABD E C
A A A A A

E
Data Structure and Applications E E E E
Nagaraj Bhat, SMVITM, Udupi
• Starting at the Root (A):
Preorder C Function –

The function is initially called with root = A.
Check if A is NULL: A is not NULL, so the function proceeds.
– Visit A: A is printed. Output so far: A
#include <stdio.h> – The function calls preorder(A->left), moving to B.
• At Node B:
– The function is now at B.
– Check if B is NULL: B is not NULL, so the function proceeds.
struct Node { – Visit B: B is printed. Output so far: A B
– The function then calls preorder(B->left), moving to D.
char data; • At Node D:
struct Node *left; –

The function is now at D.
Check if D is NULL: D is not NULL, so the function proceeds.
struct Node *right; –

Visit D: D is printed. Output so far: A B D
The function calls preorder(D->left), which returns immediately because D->left is NULL.
}; – The function calls preorder(D->right), which returns immediately because D->right is NULL.
• Back to Node B:
struct Node *root = NULL; – After finishing D, the function returns to B.
– The function calls preorder(B->right), moving to E.
void preorder(Node root) { • At Node E:
if (root == NULL) return; –

The function is now at E.
Check if E is NULL: E is not NULL, so the function proceeds.

printf("%c ", root->data); –



Visit E: E is printed. Output so far: A B D E
The function calls preorder(E->left), which returns immediately because E->left is NULL.
preorder(root->left); – The function calls preorder(E->right), which returns immediately because E->right is NULL.
• Back to Node A:
preorder(root->right); – After finishing the left subtree of A, the function returns to A.
– The function calls preorder(A->right), moving to C.
} • At Node C:
– The function is now at C.
– Check if C is NULL: C is not NULL, so the function proceeds.
– Visit C: C is printed. Output so far: A B D E C
– The function calls preorder(C->left), which returns immediately because C->left is NULL.
– The function calls preorder(C->right), which returns immediately because C->right is NULL.

– The final output of the inorder preorder for the given tree is: A BDEC
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
3. Postorder Traversal
• Definition: In Postorder traversal, the A
nodes are visited in the following order:
– Traverse the left subtree.
– Traverse the right subtree.
– Visit the root node.
• Pattern: Left -> Right -> Root E
DE B C A
A A A A A

E
Data Structure and Applications E E E E
Nagaraj Bhat, SMVITM, Udupi
• Starting at the Root (A):
Postorder C Function –

The function is initially called with root = A.
Check if A is NULL: A is not NULL, so the function proceeds.
– The function calls postorder(A->left), moving to B.
#include <stdio.h> • At Node B:
– The function is now at B.
– Check if B is NULL: B is not NULL, so the function proceeds.

struct Node { •
The function then calls postorder(B->left), moving to D.
At Node D:
char data; – The function is now at D.
– Check if D is NULL: D is not NULL, so the function proceeds.
struct Node *left; – D has no left child, so postorder(D->left) returns immediately because D->left is NULL.
– D has no right child, so postorder(D->right) returns immediately because D->right is NULL.
struct Node *right; – Visit D: D is printed. Output so far: D
}; • Back to Node B:
– After finishing D, the function returns to B.
struct Node *root = NULL; – The function calls postorder(B->right), moving to E.
• At Node E:
void postorder(Node root) { – The function is now at E.
if (root == NULL) return; – Check if E is NULL: E is not NULL, so the function proceeds.
– E has no left child, so postorder(E->left) returns immediately because E->left is NULL.
postorder(root->left); – E has no right child, so postorder(E->right) returns immediately because E->right is NULL.
– Visit E: E is printed. Output so far: D E
postorder(root->right); • Back to Node B:
printf("%c ", root->data); – After finishing the left and right subtrees of B, the function returns to B.
– Visit B: B is printed. Output so far: D E B
} • Back to Node A:
– After finishing the left subtree of A, the function returns to A.
– The function calls postorder(A->right), moving to C.
• At Node C:
– The function is now at C.
– Check if C is NULL: C is not NULL, so the function proceeds.
– C has no left child, so postorder(C->left) returns immediately because C->left is NULL.
– C has no right child, so postorder(C->right) returns immediately because C->right is NULL.
– Visit C: C is printed. **Output so far: D E B C

Data Structure and Applications • Back to Node A: Nagaraj Bhat, SMVITM, Udupi
– After finishing the left and right subtrees of A, the function returns to A.
Tree Traversals: An Example

B C

D E F

G
Preorder: (Root->Left->Right)
Postorder: (Left->Right->Root)
In Order: (Left->Root->Right)
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Tree Traversals: An Example

B C

D E F

Preorder: A
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: AB
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABD
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABDE
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABDEC
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABDECF
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABDECFG
(visit each node as your reach it)
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder:
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder:
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: D
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DE
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEB
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEB
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEB
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEBG
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEBGF
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEBGFC
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Postorder: DEBGFCA
G

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order:

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order:

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: D

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DB

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBE

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBEA

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBEA

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBEAF

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBEAFG

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

G
In Order: DBEAFGC

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: An Example

B C

D E F

Preorder: ABDECFG
Postorder: DEBGFCA
G
In Order: DBEAFGC

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHIECG
Postorder: HIFDEBGCA
In Order: DHFIBEACG
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: A

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: AB

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABD

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDF

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFH

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHI

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHIE

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHIEC

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHIECG

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder:

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder:

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder:

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder:

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: H

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HI

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIF

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFD

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDE

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDEB

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDEB

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDEBG

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDEBGC

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Postorder: HIFDEBGCA

H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order:
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order:
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: D
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: D
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DH
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHF
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFI
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFIB
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFIBE
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFIBEA
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFIBEAC
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

In Order: DHFIBEACG
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Tree Traversals: Another Example
A

B C

D E

Preorder: ABDFHIECG
Postorder: HIFDEBGCA
In Order: DHFIBEACG
H I

Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi


Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
Data Structure and Applications Nagaraj Bhat, SMVITM, Udupi
n-gl.com

You might also like