Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Module-3 22 Scheme

The document discusses various operations on linked lists such as concatenating two linked lists, searching a linked list, inverting a singly linked list, finding the length of a circular linked list, and traversing a singly linked list. It also discusses sparse matrix representation using linked lists and operations on doubly linked lists such as insertion and deletion.

Uploaded by

jexehif373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Module-3 22 Scheme

The document discusses various operations on linked lists such as concatenating two linked lists, searching a linked list, inverting a singly linked list, finding the length of a circular linked list, and traversing a singly linked list. It also discusses sparse matrix representation using linked lists and operations on doubly linked lists such as insertion and deletion.

Uploaded by

jexehif373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Regulation 2022 DSA(BCS304)

MODULE 3: LINKED LISTS , TREES

ADDITIONAL LIST OPERATIONS

Concatenation a 2 linked list


listPointer concatenate(listPointer ptr1, listPointer ptr2)
{
if(!ptr)
return ptr2;
if(!ptr2)
return ptr1;
for (temp=ptr1; temp->link!=NULL; temp=temp->link);
temp->link=ptr2;
}
Traversal: Initially, we traverse through the first linked list until we reach its last node (where the
next pointer is NULL). This allows us to locate the end of the first list.
Pointer Manipulation: Once we've reached the end of the first list, we adjust the next pointer of the
last node of the first list to point to the head of the second list. This action effectively connects the two
lists.
Resulting Concatenated List: After this manipulation, the first linked list now includes all the nodes
from the original list, followed by all the nodes from the second list.
Handling Edge Cases: If either list is empty (NULL), the concatenation operation becomes simpler.
If the first list is empty, returning the second list would be sufficient. If the second list is empty, the
first list already stands as the concatenated list.
Memory Management: Remember to manage memory appropriately by freeing any unused nodes
or lists to avoid memory leaks.

Search in a linked list:


bool search(struct Node* head, int x)
{
// Initialize current
struct Node* temp = head;
Regulation 2022 DSA(BCS304)
while (temp != NULL)
{
if (temp->key == x)
return true;
temp= temp->next;
}
return false;
}
Comparison: At each node, compare the value stored in that node with the value you are searching
for. If there's a match, the search is successful, and you've found the node containing the desired value.
Handling Not Found: If the value is not found in any node during traversal, the search concludes when
reaching the end of the list (when the next pointer of the current node is NULL). In this case, it means
the value is not present in the linked list.
Inverting a singly linked list:
Regulation 2022 DSA(BCS304)

Finding length of a circular linked list:

Search an Element on a Linked List

search an element on a linked list using a loop using the following steps. We are finding item on a
linked list.

• Make head as the current node.

• Run a loop until the current node is NULL because the last element points to NULL.

• In each iteration, check if the key of the node is equal to item. If it the key matches the item,
return true otherwise return false.

searchNode(struct Node *head, int key)

struct node *temp= *head;

while (temp != NULL)

if (temp->data == key)

printf(“success”);
Regulation 2022 DSA(BCS304)
ptr = ptr->next;

return false;

Traversing of a singly linked list:Traverse each element node of the list display values of list.

void traversing (struct node *head)


{
struct node*head,*ptr;
ptr=head;
while(ptrnext!=null)
{
printf(“%d”,ptrdata);
ptr=ptrnext;
}
}
Concatenation of Linked List
Algorithm for concatenation

Let us assume that the two linked lists are referenced by head1 and head2 respectively.
1. If the first linked list is empty then return head2.
2. If the second linked list is empty then return head1.
3. Store the address of the starting node of the first linked
list in a pointer variable, say p.
4. Move the p to
the last node of the linked list through simple linked list traversal
technique.
5. Store the address of the first node of the second linked
list in the next field of the node pointed by p. Return head1.
Regulation 2022 DSA(BCS304)
struct node * concatenate (node *head1, node *head2)
{
node *p;
if (head1==NULL) //if the first linked list is empty
return (head2);
if (head2==NULL) //if second linked list is empty
return (head1);
p=head1; //place p on the first node of the first linked list

while (p->next!=NULL) //move p to the last node


p=p->next;
p->next=head2; //address of the first node of the
second linked list stored in the
last node of the first linked list

return(head1);
}

SPARSE MATRIX REPRESENTATION

A linked list representation for sparse matrices.

In data representation, each column of a sparse matrix is represented as a circularly linked list
with a header node. A similar representation is used for each row of a sparse matrix.
Each node has a tag field, which is used to distinguish between header nodes and entry nodes.

Header Node:

• Each header node has three fields: down, right, and next as shown in figure (a).
• The down field is used to link into a column list and the right field to link into a row list.

• The next field links the header nodes together.


• The header node for row i is also the header node for column i, and the total
number of header nodes is max {number of rows, number of columns}.

Element node:

• Each element node has five fields in addition in addition to the tag field: row, col, down,
right, value as shown in figure(b).
Regulation 2022 DSA(BCS304)
• The down field is used to link to the next nonzero term in the same column and the right
field to link to the next nonzero term in the same row. Thus, if a ij ≠ 0, there is a node with
tag field = entry, value = a ij, row = i, and col = j as shown infigure (c).

• We link this node into the circular linked lists for row i and column j. Hence, it is
simultaneously linked into two different lists.
Regulation 2022 DSA(BCS304)
Consider the sparse matrix, as shown in the figure (2).
Figure (3) shows the linked representation of this matrix. Although we have not shown the value of
the tag fields, we can easily determine these values from the node structure.
For each nonzero term of a, have one entry node that is in exactly one row list and one column list.
The header nodes are marked HO-H3. As the figure shows, we use the right field of the header node
list header to link into the list of header nodes.

To represent a numRows x numCols matrix with numTerms nonzero terms, then we need max
{numRows, numCols} + numTerms + 1 nodes. While each node may require several words of
memory, the total storage will be less than numRows x numCols when numTerms is sufficiently
small.

There are two different types of nodes in representation, so unions are used to create the appropriate
data structure. The C declarations are as follows:

#define MAX-SIZE 50 /*size of largest matrix*/ typedef enum {head,


entry} tagfield; typedef struct matrixNode *matrixPointer;
typedef struct {
int row;
int col;
int value;
} entryNode;

typedef struct {
matrixPointer down;
matrixPointer right;
tagfield tag;
union {
matrixPointer next;
entryNode entry;
} u;
} matrixNode; matrixPointer hdnode[MAX-SIZE];

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

DOUBLY LINKED LIST


1. The difficulties with single linked lists is that, it is possible to traversal only in one
direction, ie., direction of the links.
2. The only way to find the node that precedes p is to start at the beginning of the list. The same
problem arises when one wishes to delete an arbitrary node from a singly linked list. Hence
the solution is to use doubly linked list
Doubly linked list: It is a linear collection of data elements, called nodes, where each node N is
divided into three parts:
1. An information field INFO which contains the data of N

2. A pointer field LLINK (FORW) which contains the location of the next node in the list

3. A pointer field RLINK (BACK) which contains the location of the preceding node in the
list
The declarations are: typedef struct node *nodePointer;
typedef struct
{
nodePointer llink;
element data;
nodePointer rlink;
} node;

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

Insertion into a doubly linked list

Insertion into a doubly linked list is fairly easy. Assume there are two nodes, node and newnode, node
may be either a header node or an interior node in a list. The function dinsert performs the insertion
operation in constant time.

void dinsert(nodePointer node, nodePointer newnode)


{/* insert newnode to the right of node */
newnode→llink = node;
newnode→rlink = node→rlink;
node→rlink→llink = newnode;
node→rlink = newnode;
}
Program: Insertion into a doubly linked circular list
Deletion from a doubly linked list
Deletion from a doubly linked list is equally easy. The function ddelete deletes the node deleted
from the list pointed to by node.
To accomplish this deletion, we only need to change the link fields of the nodes that precede
(deleted→llink→rlink) and follow (deleted→rlink→llink) the node we want to delete.
void ddelete(nodePointer node, nodePointer deleted)
{/* delete from the doubly linked list */
if (node == deleted)
printf("Deletion of header node not permitted.\n");
else {
deleted→llink→rlink = deleted→rlink;
deleted→rlink→llink = deleted→llink;
free(deleted) ;
}

Algorithms:
Insertion at the Beginning
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
1. START
2. Create a new node with three variables: prev, data, next.
3. Store the new data in the data variable
4. If the list is empty, make the new node as head.
5. Otherwise, link the address of the existing first node to the next variable of the new node, and assign
null to the prev variable.
6. Point the head to the new node.
7. END
Insertion at the End
1. START
2. If the list is empty, add the node to the list and point the head to it.
3. If the list is not empty, find the last node of the list.
4. Create a link between the last node in the list and the new node.
5. The new node will point to NULL as it is the new last node.
6. END

Deletion at the Beginning


1. START
2. Check the status of the doubly linked list
3. If the list is empty, deletion is not possible
4. If the list is not empty, the head pointer is shifted to the next node.
5. END

Doubly linked list program.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Structure to represent employee data
struct Employee {
char ssn[20];
char name[50];
char dept[50];
char designation[50];
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
float sal;
long long int phNo;
struct Employee *prev;
struct Employee *next;
};
typedef struct Employee Employee;
Employee *head = NULL;
Employee *tail = NULL;

// Function to create a new employee node


Employee *createEmployee() {
Employee *newEmployee = (Employee *)malloc(sizeof(Employee));
if (newEmployee == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
printf("Enter SSN: ");
scanf("%s", newEmployee->ssn);
printf("Enter Name: ");
scanf("%s", newEmployee->name);
printf("Enter Department: ");
scanf("%s", newEmployee->dept);
printf("Enter Designation: ");
scanf("%s", newEmployee->designation);
printf("Enter Salary: ");
scanf("%f", &newEmployee->sal);
printf("Enter Phone Number: ");
scanf("%lld", &newEmployee->phNo);
newEmployee->prev = NULL;
newEmployee->next = NULL;
return newEmployee;
}
// Function to insert an employee at the end of the list
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
void insertEnd() {
Employee *newEmployee = createEmployee();
if (head == NULL) {
head = newEmployee;
tail = newEmployee;
} else {
newEmployee->prev = tail;
tail->next = newEmployee;
tail = newEmployee;
}
printf("Employee added at the end.\n");
}
// Function to delete an employee from the end of the list
void deleteEnd() {
if (head == NULL) {
printf("List is empty, cannot delete.\n");
} else if (head == tail) {
free(head);
head = NULL;
tail = NULL;
printf("Employee deleted from the end.\n");
} else {
Employee *temp = tail;
tail = tail->prev;
tail->next = NULL;
free(temp);
printf("Employee deleted from the end.\n");
}
}
// Function to insert an employee at the front of the list
void insertFront() {
Employee *newEmployee = createEmployee();
if (head == NULL) {
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
head = newEmployee;
tail = newEmployee;
} else {
newEmployee->next = head;
head->prev = newEmployee;
head = newEmployee;
}
printf("Employee added at the front.\n");
}
// Function to delete an employee from the front of the list
void deleteFront() {
if (head == NULL) {
printf("List is empty, cannot delete.\n");
} else if (head == tail) {
free(head);
head = NULL;
tail = NULL;
printf("Employee deleted from the front.\n");
} else {
Employee *temp = head;
head = head->next;
head->prev = NULL;
free(temp);
printf("Employee deleted from the front.\n");
}
}
// Function to display the status of the linked list and count the number of nodes
void displayAndCount() {
if (head == NULL) {
printf("List is empty.\n");
} else {
Employee *current = head;
int count = 0;
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
printf("Employee Data:\n");
while (current != NULL) {
printf("SSN: %s, Name: %s, Department: %s, Designation: %s, Salary: %.2f, Phone:
%lld\n",
current->ssn, current->name, current->dept, current->designation, current->sal,
current->phNo);
current = current->next;
count++;
}
printf("Total Employees: %d\n", count);
}
}
int main() {
int choice;
while (1) {
printf("\nMenu:\n");
printf("1. Insert at End\n");
printf("2. Delete from End\n");
printf("3. Insert at Front\n");
printf("4. Delete from Front\n");
printf("5. Display and Count\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insertEnd();
break;
case 2:
deleteEnd();
break;
case 3:
insertFront();
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
break;
case 4:
deleteFront();
break;
case 5:
displayAndCount();
break;
case 6:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}

HEADER LINKED LISTS


A header linked list is a linked list which contains a special node, called the header node, at the
beginning of the list.
The following are two kinds of widely used header lists:
1. A grounded header list is a header list where the last node contains the null pointer.

2. A circular header list is a header list where the last node points back to the headernode.
Below figure contains schematic diagrams of these header lists.

Observe that the list pointer START always points to the header node.

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)
• If START→LINK = NULL indicates that a grounded header list is empty

• If START→LINK = START indicates that a circular header list isempty.


The first node in a header list is the node following the header node, and the location of the first
node is START→LINK, not START, as with ordinary linked lists.

Below algorithm, which uses a pointer variable PTR to traverse a circular header list 1.
Begins with PTR = START→LINK (not PTR = START)
2. Ends when PTR = START (not PTR = NULL).
Algorithm: (Traversing a Circular Header List) Let LIST be a circular header list in memory.
This algorithm traverses LIST, applying an operation PROCESS to each node of LIST.
1. Set PTR: = START→LINK. [Initializes the pointer PTR.]
2. Repeat Steps 3 and 4 while PTR ≠ START:

3. Apply PROCESS to PTR→INFO.

4. Set PTR: = PTR→LINK. [PTR now points to the next node.] [End of Step 2 loop.]

5. Exit.

Algorithm: SRCHHL (INFO, LINK, START, ITEM, LOC)

LIST is a circular header list in memory. This algorithm finds the location LOC of the node where
ITEM first appears in LIST or sets LOC = NULL.
1. Set PTR: = START→LINK

2. Repeat while PTR→INFO [PTR] ≠ ITEM and PTR ≠ START: Set PTR: =PTR→LINK.
[PTR now points to the next node.] [End of loop.]
3. If PTR→INFO = ITEM, then: Set
LOC: = PTR.
Else:

Set LOC: = NULL.

[End of If structure.]
4. Exit.
The two properties of circular header lists:
1. The null pointer is not used, and hence all pointers contain valid addresses.

2. Every (ordinary) node has a predecessor, so the first node may not require a special case.
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
There are two other variations of linked lists

1. A linked list whose last node points back to the first node instead of containing the null
pointer, called a circular list
2. A linked list which contains both a special header node at the beginning of the list and a
special trailer node at the end of the list

Trees
Introduction
Definition of Tree:
A tree is a finite set of one or more nodes such that
There is a special node called the root.
The remaining nodes are partitioned into n ≥ 0 disjoint sets T1, , Tn, where each of these sets
are called the subtrees of the root.

Example: Consider the tree given below

Figure 4.1 A sample Tree

The tree has 13 nodes and has one character as its information. A tree is always drawn with its root at
the top. Here the node A is the root.

 Degree of a node: The number of subtrees of a node is called its degree.


o Example : The degree of A = 3, C = 1, and of F = 0.
 Degree of a Tree :The degree of a tree is the maximum degree of the nodes in the tree. The
tree shown in the example has degree 3.
 Leaf or terminal nodes or external nodes: Nodes that have degree zero is called the leaf
nodes Example : {K,L,F,G,M,I,J} is the set of leaf nodes
 Non-terminal nodes/internal nodes : Nodes that have at least a degree one or two. (nodes
other than the leaf nodes ) oExample : {B,C,D,E,F,H,A} is the set of Non-terminal nodes

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)
 Siblings : Children of the same parent are said to be siblings Example : {H,I,J} are siblings.
 The ancestors: all the nodes along the path from the root to that node.
o Example : The ancestors of M are A, D, and H.
 The level of a node is .The root is considered be at level one[1]. If a node is at level l, then its
children are at level l + 1.
 The height or depth is maximum level of any node in the tree. Thus, the depth of the tree in
the example is 4.

Binary Trees

The Abstract Data type

Definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two
disjoint binary trees called the left subtree and the right subtree.
Objects: a finite set of nodes either empty or consisting of a root node, left Binary_Tree, and right
Binary_Tree.
Functions: for all bt,bt1,bt2 ∈ BinTree, item ∈ element

BinTree Create() ::= creates an empty binary tree

Boolean IsEmpty(bt) ::= if (bt == empty binary tree) return TRUE else return FALSE

return a binary tree whose left subtree is bt1, whose right subtree
BinTree MakeBT(bt1, item,bt2)
is bt2, and whose root node contains the data item.
::=

BinTree Lchild(bt) ::= if (IsEmpty(bt)) return error else return the left subtree of bt.

Element Data(bt) ::= if (IsEmpty(bt)) return error else return the data in the root
node of bt.

BinTree Rchild(bt) ::= if (IsEmpty(bt)) return error else return the right subtree of bt

Difference between binary tree and tree.

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

Binary tree Tree

Empty tree exist No tree exist with zero nodes

Order of the child is considered Order of the child is not considered

Each node can be partitioned to only two Each node can be partitioned to T1,T2…..Tn
disjoint subtrees disjoint subtrees

Properties of Binary Tree


Lemma 1: [Maximum number of nodes]
.
1. The maximum number of nodes on level i of a binary tree is 2i-1, i ≥ 1 Proof:
The proof is by induction on i.

Induction Base: The root is the only node on level i = 1. Hence, the maximum number of
nodes on level i = 1 is 2 i-1 = 20 = 1.

Induction Hypothesis: Let i be an arbitrary positive integer greater than 1. Assume that the
maximum number of nodes on level i - 1 is 2i-2.

Induction Step:
The maximum number of nodes on level i - 1 is 2i-2 by the induction hypothesis.
Since each node in a binary tree has a maximum degree of 2, the maximum number of nodes
on level i is two times the maximum number of nodes on level i-1, i.e 2* 2i-2 = 2i-1
Hence Prooved

2. The maximum number of nodes in a binary tree of depth k is 2k - 1, k ≥ 1. The


maximum number of nodes in a binary tree of depth k is

Lemma 2: [Relation between number of leaf nodes and degree-2 nodes]: For any non empty binary
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
tree, T, if n0 is the number of leaf nodes and n2 the number of nodes of degree 2, then n0 = n2 + 1.
Proof:
Let n1 be the number of nodes of degree one and n the total number of nodes. Since all
nodes in T are at most of degree two, we have n=n0+n1+n2 --------- (1)
If we count the number of branches in a binary tree, we see that every node except the root has
a branch leading into it.
If B is the number of branches, then n = B + 1 --------- (2)
All branches stem out from a node of degree one or two. Thus,
B = n1 + 2n2. Hence, we obtain -- (-3)
Sum of the branches that stem out of a node(outdegree) is always equal to the sum of the
branches that stem into a node(indegree). Therefore Substitutuing eq(3) in eq(2) n=B+1
n= n1 + 2n2 +1 (4)
Subtracting Eq. (4) from Eq. (1) and rearranging terms, we get n0
= n2 + 1
Definition
Full Binary Tree: A full binary tree of depth k is a binary tree of depth k having 2k - 1 nodes, k ≥ 0.
Example

Figure 4.6 Full Binary tree of depth 4

The nodes are numbered in a full binary tree starting with the root on level 1, continuing with the nodes
on level 2, and so on. Nodes on any level are numbered from left to right.

Complete binary tree : A binary tree is complete if the number of nodes in each level i except possibly
the last level is 2i-1. The number of nodes in the last level appears as left as possible.
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
Example: A complete tree T11 with 11 nodes is shown below. This is not a full binary tree.

Complete Binary Tree


Extended Binary tree
• A binary tree T is said to be a 2-tree or an extended binary tree if each node N has either 0 or
2 children.
• The nodes with 2 children are called internal nodes and the nodes with 0 children are called
external nodes. Sometimes the nodes are distinguished in diagrams by using circles for internal
nodes and squares for external nodes
• The term extended binary tree comes from the operation where tree T is converted into a 2-
tree by replacing each empty subtree by new node and the new tree is a 2-tree . The nodes in
the original tree T are internal nodes in the extended tree and the new nodes are the external
nodes in the extended tree.

Strictly Binary Tree is a tree where every non leaf node in a binary tree has non empty left and right
subtrees. A strictly binary tree with n leaves always contain 2n-1 nodes

Example:

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

Example For a Strictly Binary Tree


Almost Complete Binary Tree: A binary tree of depth d is an almost complete binary tree if
a. A node n at level less than d-1 has two sons

b. For any node n in the tree with a right descendant at level d, n must have a left son and every
left descendant of n is either a leaf at level d or has two sons

Example

Almost Complete Binary Tree.

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)
Binary Tree representations
Array Representation: If a complete binary tree with n nodes is represented sequentially, then
for any node with index i, 1 ≤ i ≤ n, we have

 parent (i) is at [i / 2] if i ≠ 1. If i = 1, i is at the root and has no parent.

 leftChild (i) is at 2i if 2i ≤ n. If 2i > n, then i has no left child.


 rightChild (i) is at 2i + 1 if 2i + 1 ≤ n. If 2i + 1 > n, then i has no right child.

Example

Array representation of tree


This representation can be used for any binary tree. In most cases there will be a lot of unutilized
spaces. For complete binary tree it will be good.
Linked Representation
Disadvantage of array representation
• The array representation is good for complete binary trees but, it wastes a lot of space for many
other binary trees.
• Insertion and deletion of nodes from the middle of a tree require the movement of potentially
many nodes to reflect the change in level number of these nodes.
• These problems can be overcome easily through the use of a linked representation.
Each node has three fields, leftChild, data, and rightChild.
A node can be defined as:
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
struct node
{
int data;
struct node * leftChild;
struct node * rightChild;
};
typedef struct node TreeNode;
A node in a tree can be represented as follows

leftchild Data rightchild data

Leftchild Rightchild

Node Representation

With this node structure it is difficult to determine the parent of a node, If it is necessary to be able to
determine the parent of random nodes, then a fourth field, parent, may be included in the class

Linked Representation of Skewed Tree

Linked Representation of Complete Tree

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

Binary Tree Traversals


• Traversing a tree is visiting each node in the tree exactly once.
• When a node is visited, some operation (such as outputting its data field) is performed on
it. A full traversal produces a linear order for the nodes in a tree.
• When traversing a tree each node and its subtrees must be treated in the same fashion.
Based on this there are three types of traversals inorder, preorder and postorder traversals.
Inorder Traversal
• Inorder traversal move down the tree toward the left until we can go no farther.
• Then "visit" the node,
• move one node to the right and continue.
• If we cannot move to the right, go back one more node and continue
• A precise way of describing this traversal is by using recursion as follows

void inorder(TreeNode * ptr)


{
if (ptr)
{
inorder(ptr→leftChild);
printf("%d",ptr→data);
inorder(ptr→rightChild);
}
}

Preorder Traversal
• visit a node
• traverse left, and continue.
• When you cannot continue, move right and begin again or move back until you can move
right and resume."

void preorder(TreeNode *ptr)


{
if (ptr)
Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)
{
printf("%d",ptr→data);
preorder(ptr→leftChild);
preorder(ptr→rightChild);
}
}

Postorder Traversal
• traverse left, and continue.
• When you cannot continue, move right and traverse right as far as possible
• Visit the node

void postorder(TreeNode *ptr)


{
if(ptr)
{
postorder(ptr→leftChild);

postorder(ptr→rightChild);

printf("%d",ptr→data);
}
}
Example:
Inorder Traversal: DGBAHEICF
Preorder Traversal: ABDGCEHIF
Postorder Traversal: GDBHIEFCA

Expression Tree: An expression containing operands and binary operators can be represented by a
binary tree.
Representation and traversal of expression tree
A node representing an operator is a non leaf. A node representing an operand is a leaf. The root of
the tree contains the operator that has to be applied to the results of
evaluating the left subtree and theright subtree.

Example1: A+ B * C can be represented as follows


Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal
Regulation 2022 DSA(BCS304)

When the binary expression trees are traversed preorder we get the preorder expression. When we
traverse the tree postorder we get the postorder expression . When we traverse it inorder we get the
inorder expression.

For Example : consider the traversals for the tree given above

Inorder traversal giving rise to infix expression A+B*C


Preorder traversal giving rise to prefix expression +A*BC
Postorder traversal giving rise to postfix expression ABC*+

Example2: A+(B-C)*D$(E*F) is represented as follows

Inorder traversal giving rise to infix expression A+(B-C)*D$(E*F)

Preorder traversal giving rise to prefix expression : +A*-BC$D*EF

Postorder traversal giving rise to postfix expression : ABC-DEF*$*+


Evaluation of Expression Tree
Example:

Result = 3

Prepared by Sowmya H D, Asst prof, CSE SSCE, Anekal


Regulation 2022 DSA(BCS304)

Threaded Binary Tree


Threads
A binary tree has more NULL links than pointers. These null links can be replaced by special
pointers, called threads, to other nodes in the tree.
Two way threading
To construct the threads we use the following rules (assume that ptr represents a node):
• If ptr → leftChild is null, replace ptr → leftChild with a pointer to the inorder
predecessor of ptr.
• If ptr → rightChild is null, replace ptr → rightChild with a pointer to the inorder
successor of ptr.

One way threading: If ptr → rightChild is null, replace ptr → rightChild with a pointer to the
inorder successor of ptr. Ptr->left child remains unchanged.

Note : unless specified we consider threading corresponds to the inorder traversal. To distinguish
the threads from ordinary pointers, threads are always drawn with broken links

Example: Consider the binary tree and the corresponding threaded tree given below

Binary tree
Regulation 2022 DSA(BCS304)

Threaded Binary Tree


• When we represent the tree in memory, we must be able to distinguish between
threads and normal pointers.
• This is done by adding two additional fields to the node structure, leftThread and
rightThread.
• Assume that ptr is an arbitrary node in a threaded tree.
o If ptr → leftThread = TRUE, then ptr→ leftChild contains a thread;
otherwise it contains a pointer to the left child.
o Similarly, if ptr → rightThread = TRUE, then ptr → rightChild contains a
thread; otherwise it contains a pointer to the right child.

This node structure is defined as follows


struct node
{
short int leftThread;
struct node * leftChild;
char data;
thread node *rightChild;
short int rightThread;
};
typedef struct node ThreadNode;

• In Figure two threads have been left dangling: one in the left child of H, the other in the
right child of G.
• To avoid loose threads, a header node is assumed for all threaded binary trees.
• The original tree is the left subtree of the header node.
• An empty binary tree is represented by its header node as in figure below

leftthread leftchild data Rightchild rightthread


True false
Regulation 2022 DSA(BCS304)

Empty threaded Binary tree

The complete memory representation for the tree is as below

t=True
f= False

Memory representation of threaded Tree

The variable root points to the header node of the tree, while root → leftChild points to the start of
the first node of the actual tree.

Inorder Traversal of a Threaded Binary Tree

By using the threads, we can perform an inorder traversal without making use of a stack.
• For any node, ptr, in a threaded binary tree, if ptr → rightThread = TRUE, the inorder
successorof ptr is ptr → rightChild by definition of the threads.
• Otherwise we obtain the inorder successor of ptr by following a path of left-child links
from the right-child of ptr until we reach a node with leftThread = TRUE.

Finding the inorder successor of a node: The function insucc finds the inorder successor
of anynode in a threaded tree without using a stack.
ThreadNode * insucc(ThreadNode *tree)
{
ThreadNode * temp;
temp = tree→rightChild;
Regulation 2022 DSA(BCS304)

if(tree→rightThread==’f’)
while(temp→leftThread==’f’)
temp =temp→leftChild;
return temp;
}

Inorder traversal of a threaded binary tree


• To perform an inorder traversal we make repeated calls to insucc
• This function assumes that the tree is pointed to by the header node's left child and
that the header node's right thread is FALSE.

void Tinorder(ThreadNode * tree)


{
ThreadNode * temp = tree;
for (;;)
{
temp = insucc(temp);
if(temp == tree)
break;
printf("%c", temp→data);
}
}*

You might also like