0% found this document useful (0 votes)
32 views64 pages

CS8391 Unit 3

Data Structure unit 3

Uploaded by

matheshmass36
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)
32 views64 pages

CS8391 Unit 3

Data Structure unit 3

Uploaded by

matheshmass36
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/ 64

Trees ADT

TREES ADT
5.1. INTRODUCTION
Tree is a non-linear data structures, (i.e. each element can be connected to more than
two adjacent elements) which represents hierarchical relationships between individual
elements. Naturally, tree grows upwards from the ground (root) into the air (Leaves). But
tree ADT grows downwards from the root to the leaves. This is a universally accepted way
of representing tree data structures.

Definition
Tree is a non-empty collection of nodes (N) & edges (N-1) that satisfies the
following requirements,

♣ It has a special data item referred as the root of the tree which not have parent.
♣ All remaining data items are partitioned into number of subsets, each of which itself
is a tree & are referred as Sub trees.
Each data item in a tree is referred as a node. Node is a basic structure of a tree & specifies
the information part of an element.
For example, consider the following tree with 8 nodes.

5.2. BASIC TERMS IN TREES ADT


1. Edge (or) Link
An edge is a connection between two nodes. Always a Tree has (N-1) number of
edges where ‘N’ is a total number of nodes in a tree.
Example: Above tree has ‘8’ nodes and ‘7’ edges (N-1).
2. Path

Data Structures Using C


Trees ADT

A path in a tree is a sequence of distinct nodes in which successive nodes are


connected by the edges in the tree.
Example: a path between A to H is given by the node pairs {A, B, F, H} or edges
{(A, B), (B, F), (F, H)}.

An important property of a tree is that there should be only one path exist
between any two nodes. If there is no path or more paths between some pair of
Note: nodes then we call the structure as a graph, not a tree.

3. Parent node and children nodes


In tree ADT, nodes are hierarchically represented like a parent-child relationship. A
parent node contains one or more child nodes which are connected through edges.
Example: B, C & D are referred as children nodes to the parent node ‘A’

4. Levels
The tree is organized in level to maintain the hierarchical relationship between
them. The entire tree structure is leveled in such a way that if a node is at level ‘n’, then its
children will be at level ‘n+1’. In general, the root node is always at level 1 then its
immediate children are at level 2 and so on. The child nodes of a parent are one level lower
than the parent node.

5. Root
A parent node in first level (i.e. 1th level) of tree is referred as a root node. A root
node does not have parent node.
Example: from the above tree ‘A’ is referred as the root node.

6. Branch
A Link between a parent node & its child node is also referred as a branch. All the
nodes in a tree, except the leaf node must have a branch.
Example: Node B has two branches namely E & F.

7. Siblings
The child node of a parent node is referred as siblings of the other child/children of
same parent.
Example: C & D are the siblings to ‘B’.

8. Subtree
It is a subset of tree that is itself a tree. If you remove the root then it becomes a
forest (i.e. subtrees are become a individual tree with its own root)
Example: If you remove the root ‘A’ then it becomes a forest with 3 trees namely B,
C & D.

Data Structures Using C


Trees ADT

9. Degree
The number of sub trees for a node is referred as its degree.
Example: The degree of root node ‘A’ is 3. The degree of ‘F’ is 1.

10. Ancestors
The ancestors of a node are all the nodes along the path from the root to that node.
The root node of the tree is the ancestor of the entire node in the tree.
Example: the ancestor of node ‘H’ is A, B & F

11. Leaf (or) Terminal node


A node that has no children is called as a leaf node (i.e. a node with 0 degree). All
the other intermediate nodes or parent nodes are called as Non-terminal nodes.
Example: E, G, H are terminal nodes & A, B, C, D, F are Non-terminal nodes.

12. Height
Height of a tree is defined as the maximum level of any node in the tree. Height of a
node is a number of nodes from that node to the leaf at maximum level.
Example: The height of the tree is ‘4’. The height of the node ‘B’ is 3.

13. Depth
Depth and height of the tree is same. Depth of a node is a number of nodes from
root to that node.
Example: The depth of the tree is ‘4’. The depth of the node ‘F’ is 3.

5.3. APPLICATIONS & VARIATIONS OF TREES ADT


In general, trees are very useful abstractions in computer science field. They are,
✔ Trees are used to implement the file system of several popular operating systems.
✔ Used to evaluate arithmetic expressions.
✔ Used to support the search operations in O(log N) average time.

VARIATIONS OF TREES ADT


1. Binary Tree
2. Threaded Binary Tree
3. Binary Search Tree
4. Heap Tree
5. AVL Tree
6. B Tree
7. B+ Tree
8. Splay Tree

5.4. BINARY TREE ADT

Data Structures Using C


Trees ADT

One of the most important tree structures is the binary tree. A binary tree is a tree in
which a node should have either no child or not more than two children. Each node in the
binary tree has 2 subtrees,

♣ Left subtree: All the nodes to the left child of a given node in a binary tree.
♣ Right subtree: All the nodes to the right child of a given node in a binary
tree.

5.4.1. TYPES OF BINARY TREE


1. Left skewed binary tree
In a binary tree structure, the entire node has left child alone then it is
referred as a Left skewed binary tree.

2. Right skewed binary tree


In a binary tree structure, the entire node has right child alone then it is
referred as a right skewed binary tree.

3. Full binary tree

Data Structures Using C


Trees ADT

It is a binary tree structure, in which every non-leaf node has exactly 2


children and leaf nodes are not necessarily to be on the same level of tree.

4. Perfect binary tree


It is a binary tree structure, in which every non-leaf node has exactly 2
children and leaf nodes are must be on the same level of tree.

5. Extended binary tree


An extended binary is a transformation of a binary tree into a complete
binary tree, which replaces every null sub tree in original binary tree with special nodes.
The nodes in the original binary tree are referred as internal nodes, while the special
nodes in complete binary tree (Square shape) are referred as external nodes.

6. Complete binary tree


It is a binary tree structure, in which every non-leaf node has less than or
equal to two children and leaf nodes are not necessarily to be on the same level of
tree. The leaves should be in either the level (h-1) or level (h-2) i.e. either last or

Data Structures Using C


Trees ADT

previous than last levels, where h is a height of binary tree. A node must be filled
from leftmost to rightmost in each level.

PROPERTIES OF BINARY TREE


♣ The number of leaves in the binary tree is equal to the number of nodes with two
children + 1.
♣ A binary tree of height ‘h’ has at least h and at most (2h -1) nodes in it, where h>0.

5.4.2. REPRESENTATION OF BINARY TREES ADT


Implementation of binary tree can be made by using two different data structures.
They are,
1. Linear representation (using array data structure)
2. Linked representation (using linked list data structure)

5.4.2.1.LINEAR REPRESENTATION
It is a simple way to implement a binary tree ADT. Binary tree can be represented
by using single dimensional array with the size of (2h) where ‘h’ is the height of a binary
tree. According to the property of binary tree, it should have maximum of 2h-1 node. So
that only, the array size is declared with respect to the height of the tree. Moreover, the 0th
index in array is not used for storing the binary tree elements. Therefore, the size of array
should be 2h instead of 2h-1.
For Example,

Algorithm for creating the binary tree


Step-1: Store the value of root node in the first location of array (i.e. index=1).
Step-2: The left child of nth index node is stored at the location (2n)th index.

Data Structures Using C


Trees ADT

Step-3: The right child of nth index node is stored at the location (2n+1)th index.
Step-4: If there is no left or right child, the array location is left as empty.

For Example, consider the above binary tree structure. The array representation becomes,

Algorithm (searching a node which has a parent / right child / left child)
Step-1: Parent of ith index node is at (i/2)th index location, where i >1. If i=1 then it is the
root node of the tree which has no parent node.
Step-2: Left child of ith index node is at 2ith index position of array where 2i<=N where
N is the array size. If 2i>N then the ith index node has no left child.
Step-3: Right child of ith index node is at (2i+1)th position of array where (2i+1) <=N. If
(2i+1)>N then the ith index node has no right child.
To verify whether a parent or left or right child exists in a tree or not, the following
algorithm is used. For Example, take node ‘B’ which is stored in 3rd index position of
array.
✔ Left child node of B is in 3*2=6th index position in array (i.e.) node ‘C’.
✔ Right child node of B is in (3*2) +1=7th index in array (i.e.) node ‘D’.
✔ Left child node of C is in (6*2) =12th index, but 12>n value. Hence there is no
left child for a node C.

Even though we didn’t implement a full binary tree, we should allocate the
memory with the size 2h which if equal to the size of full binary tree. So the
Note: memory is wasted by using array data structure.

MERITS OF BINARY TREE ADT USING ARRAY DS


1. The main advantage of representing a binary tree using array is for simplicity and
ease of implementation.
2. Any node can be accessed from any other node by calculating the index.
3. Element are stored without any pointer to its children or parent node.

DEMERITS OF BINARY TREE ADT ARRAY DS


1. In most cases, a lot of memory space will be unutilized because of empty entries in
array. A full binary tree will not waste any space. Whereas a complete binary tree
and skewed binary trees make a considerable wastage of memory space.
2. There is no way to enhance the tree structure (i.e. tree height will not be changed
after it is represented by array data structure)
3. Insertion and deletion of elements are inefficient due to data movements in array.

Data Structures Using C


Trees ADT

5.4.2.2.LINKED LIST REPRESENTATION OF BINARY TREE ADT


The demerits of binary tree representation using array is overcome by the linked list
representation. As we know that, in linked representation each node has two fields (i.e. data
field and Link field).
In binary tree, each node has maximum two children. So that a node in linked list
has three fields, (i.e.) left child field (Lfield), right child field (Rfield) and the data field
(Dfield). If any sub tree is empty then the corresponding pointers (i.e. L field & R field)
will hold NULL value.
NODE STRUCTURE

For Example,

MERITS OF BINARY TREE ADT USING LINKED LIST DS


1. Insertion and deletion involve no data movement.
2. Memory is utilized efficiently.
3. Enhancing the tree is possible.

DEMERITS OF BINARY TREE ADT USING LINKED LIST DS


1. It is difficult to determine parent node for a given node.
2. Memory space is wasted for storing NULL pointer for the node which has one or no
sub tree. (i.e.) to store N nodes, (N+1) NULL pointers are needed.
3. This implementation requires dynamic memory allocation, which is not possible in
some programming language.

5.5. BINARY TREE TRAVERSAL

Data Structures Using C


Trees ADT

♣ One of the most important operations performed on the binary tree is tree traversal.
Traversing a binary tree means moving through all the nodes in the binary tree,
visiting each node in the tree exactly once.
♣ In List ADT, the nodes are in natural order (i.e.) from first to last, hence traversal
follows the same order. However for trees, the nodes are not in order, hence we
have to follow different procedure for traversing all the nodes.
♣ One thing to be kept in mind, while traversing a binary tree, treats each node and its
sub trees in the same manner.
♣ The task performed while traversing a binary tree are,
✔ Visiting a node (denoted by the letter ‘O’ - root).
✔ Traversing the left sub tree (denoted by the letter ‘L’).
✔ Traversing the right sub tree (denoted by the letter ‘R’).
♣ Depending upon these three tasks, there are 6 possible combinations of traversals.
They are OLR, LOR, LRO, ORL, ROL, and RLO.
♣ These 6 traversals can be reduced to 3 combinations by adopting the convention,
that we always traverse the left sub tree before the right sub tree.
♣ Therefore the final possible combinations are OLR, LOR, and LRO. These are
referred as the “Preorder”, “Inorder” and “Postorder” traversals respectively.
5.5.1. PREORDER TRAVERSAL (OLR)

Step-1: Process the root node.


Step-2: Traverse the left sub tree.
Step-3: Traverse the right sub tree.

This process is continued until visiting all the nodes in the binary tree. After processing the
node, denote the node as visited. Preorder traversal leads to prefix expressions.

IMPLEMENTATION IN C
void Preorder(s *root)
{
if (root! =NULL)
{
printf (“%d\t”,root->data);
Preorder(root->left);
Preorder(root->right);
}
}

Data Structures Using C


Trees ADT

5.5.2. INORDER TRAVERSAL (SYMMETRIC ORDER LOR)

Step-1: Traverse the left sub tree.


Step-2: Process the root node.
Step-3: Traverse the right sub tree.

Inorder traversal of a binary tree always represents the element in ascending order, and
hence the process is referred as the sorting of binary tree

IMPLEMENTATION IN C
void Inorder(s *root)
{
if (root! =NULL)
{
Inorder(root->left);
printf (“%d\t”,root->data);
Inorder(root->right);
}
}

5.5.3. POSTORDER TRAVERSAL (END ORDER LRO)

Step-1: Traverse the left sub tree.


Step-2: Traverse the right sub tree.
Step-3: Process the root node.

IMPLEMENTATION IN C
void Postorder(s *root)

Data Structures Using C


Trees ADT

{
if (root! =NULL)
{
Postorder(root->left);
Postorder(root->right);
printf (“%d\t”,root->data);
}
}

5.5.4. LEVEL ORDER TRAVERSAL


Traverse the nodes according to their levels. Process the root node at level 1 and
traverse the next level. Process the node from left most to right most in the current level
continues this process till the last level.

For example, consider the following binary trees to perform all types of traversal.

PROGRAM
/*Tree Traversal in BST*/
#include<stdio.h>
#include<conio.h>
struct node

Data Structures Using C


Trees ADT

{
int data;
struct node *left,*right;
}*root=NULL;
typedef struct node s;

int insert(int);
void preorder(s *);
void postorder(s *);
void inorder(s *);
void searchitem(int);

void main()
{
int choice,no,x;
clrscr();
while(1)
{
printf("\n1.Insertion\n2.Preorder\n3.Inorder\n4.Postorder\n");
printf("5.searching\n6.Exit\nEnter U'r choice?");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Enter the Element to insert\n");
scanf("%d",&no);
x=insert(no);
if(x==1)
printf("Successfully Inserted\n");
else
printf("Error in insertion\n");
break;
}
case 2:
{
if(root!=NULL)
{
printf("\n Preorder elements are..\n");
preorder(root);
printf("\n");
}

Data Structures Using C


Trees ADT

else
{
printf("\n No elements to display\n");
}
break;
}
case 3:
{
if(root!=NULL)
{
printf("\n Inorder elements are..\n");
inorder(root);
printf("\n");
}
else
{
printf("\n No elements to display\n");
}
break;
}
case 4:
{
if(root!=NULL)
{
printf("\n Postorder elements are..\n");
postorder(root);
printf("\n");
}
else
{
printf("\n No elements to display\n");
}
break;
}
case 5:
{
printf("Enter the element to search?");
scanf("%d",&no);
searchitem(no);
break;
}
case 6:

Data Structures Using C


Trees ADT

exit(0); break;
default:
printf("Wrong Choice\n");
}
}
}

int insert(int x)
{
s *p,*prev,*ct;
p=(s *)malloc(sizeof(s));
if(p==NULL)
{
printf("out of memory\n");
return 0;
}
p->data=x;
p->left=NULL;
p->right=NULL;
if(root==NULL)
{
root=p;
return 1;
}
prev=NULL;
ct=root;
while(ct!=NULL)
{
prev=ct;
if(p->data<ct->data)
ct=ct->left;
else
ct=ct->right;
}
if(p->data<prev->data)
prev->left=p;
else
prev->right=p;
return 1;
}

void inorder(s *p)


{

Data Structures Using C


Trees ADT

if(p!=NULL)
{
inorder(p->left);
printf("%5d\t",p->data);
inorder(p->right);
}
}

void preorder(s *p)


{
if(p!=NULL)
{
printf("%5d",p->data);
preorder(p->left);
preorder(p->right);
}
}
void postorder(s *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("%5d",p->data);
}
}
void searchitem(int sno)
{
s *tnode;
tnode=root;
while(tnode!=NULL && tnode->data!=sno)
{
if(tnode->data>sno)
tnode=tnode->left;
else
tnode=tnode->right;
}
if(tnode)
printf("Search node is present\n");
else
printf("Search node is not present in tree\n");
}

Data Structures Using C


Trees ADT

5.6. CONVERSION OF GENERAL TREE TO BINARY TREE


A general tree (i.e. a tree with nodes having any number of children) can be
converted into an equivalent binary tree using the “Left most child - right siblings”
representation.

ALGORITHM
Step-1: Process starts from the root node.
Step-2: Connect the parent to its left most child through an edge and connect the left most
child to all the nodes who are all the right siblings at the same level.
Step-3: Delete all the links from the parent node to its children except for the link to its
left most child.
Step-4: Repeat step-2 & 3 for each parent node in the general tree.
Step-5: Rotate the resultant tree to 450 for getting the clear view of binary
representation.
For example, from the tree above, node ‘B’ is the left child of ‘A’, which is
connected to all the right siblings (i.e. B-C-D-E). After that, delete the link from A-C, A-D
and A-E.

Data Structures Using C


Trees ADT

5.7. EXPRESSION TREES


An expression can be represented by using binary tree ADT. The leaves or terminal
nodes are represented by the operands such as constants or variable name and the internal
nodes are represented by the operators in the expression tree.

Data Structures Using C


Trees ADT

Let us consider the infix expression (a+b*c)+((d*e+f)*g). The expression tree for
that infix expression becomes,

Algorithm (Same as evaluation of postfix expression)


Step-1: First convert the infix expression into postfix expression using stack.
Step-2: Read expression one symbol at a time until the end of the expression.
Step-3: If it is an operand, create one node tree and push the pointer of tree onto the stack.
Step-4: If it is an operator, pop two pointers from stack and form a new tree, whose root is
the operator, left child is operand1 & right child is operand2 which is to be popped
now.
Step-5: Push this resultant tree pointer onto the stack. After the end of the expression, a
stack contains the pointer of expression tree.

Example: consider the infix expression (a+b)*(c*(d+e)). Thus calculate the


equivalent postfix expression using stack ADT. The postfix expression becomes
(ab+cde+**).
When Read a & b,

Data Structures Using C


Trees ADT

Thus the expression tree for the infix expression (a+b)*(c*(d+e)) is in Stack at last.
5.8. CREATE A BINARY TREE USING INORDER AND PREORDER TRAVERSAL

A binary tree can be formed from the inputs of Inorder & Preorder traversal or
otherwise from the Inorder & Postorder traversal.
Algorithm
RebuildBinaryTree( )
1. Pick an element from Preorder traversal and denote that as a root. Increment a
Preorder Index Variable by one.
2. Create a new tree node with the data of root element. Say tNode.
3. Find the picked element’s index in Inorder. Say inIndex.
4. Call to RebuildBinaryTree for elements before inIndex and make the built tree as
left subtree of tNode.
5. Call to RebuildBinaryTree for elements after inIndex and make the built tree as right
subtree of tNode.
6. At last, the reconstructed tree is in tNode.

Data Structures Using C


Trees ADT

For example, consider the Inorder ={D, G, B, A, H, E, I, C, F} and Preorder = {A,


B, D, G, C, E, H, I, F} of a tree. Using the above algorithm, a binary tree can be
constructed like,

Consider the left subtree, {D, G, B} of node A

Consider the left subtree, {D, G} of node B

Consider the left subtree, {G} of node D

Consider the right subtree, {H, E, I, C, F} of node A

Data Structures Using C


Trees ADT

Consider the left subtree, {H, E, I} of node C

Consider the left subtree, {H} of node E

Consider the right subtree, {I} of node E

Consider the right subtree, {F} of node C

Data Structures Using C


Trees ADT

Thus the final binary tree was obtained from the input of Inorder & Preorder traversal.

The process of creating binary tree from the Inorder & Postorder is same as the
above representation whereas in Postorder the root is always at last i.e. after the
Note: left and right subtree nodes.

IMPLEMENTATION IN C
#define NULL 0
typedef struct btree
{
int data;
struct btree *left;
struct btree *right;
}node;
node *root;
void create(int,int [ ]);
void inorder(node *),preorder(node *);
void main( )
{
int i=0,p[30],in[30];
node *list;
clrscr();
printf("enter the preorder\n");
while(1) //getting array for preorder elements
{
scanf("%d",&p[i]);
i++;
if(p[i-1]==-99)
break;
}

Data Structures Using C


Trees ADT

printf("enter the inorder\n");


i=0;
while(1) //getting array for inorder elements
{
scanf("%d",&in[i]);
i++;
if(in[i-1]==-99)
break;
}
printf("\nthe given inorder is\n");
for(i=0;in[i]!=-99;i++)
printf("%5d",in[i]);
printf("\nthe giver preorder is\n");
for(i=0;p[i]!=-99;i++)
printf("%5d",p[i]);
root=(node*)malloc(sizeof(node));
root->data=p[0]; //by default first elemnt of tree is p[0]
root->right=root->left=NULL;
for(i=1;p[i]!=-99;i++)
create(p[i],in);//creating tree for each element of preorder using inorder array
printf("\n\n\nINORDER TRAVERSAL OF THE TREE\n");
inorder(root);
printf("\n\n\nPREORDER TRAVERSAL OF THE TREE\n");
preorder(root);
getch();
}
void create(int key,int a[])
{
node *i=root,*j;
while(1)
{
if(find(i->data,a,key))//finding the position of p[i](here key)to be inserted in tree
{
if(i->left==NULL)
{
i->left=(node*)malloc(sizeof(node));
i=i->left;
i->data=key;
i->left=i->right=NULL;
break;
}
else
i=i->left;

Data Structures Using C


Trees ADT

}
else
{
if(i->right==NULL)
{
i->right=(node*)malloc(sizeof(node));
i=i->right;
i->data=key;
i->left=i->right=NULL;
break;
}
else
i=i->right;
}
}
}
int find(int t,int a[],int key)
{
int i,j;
for(i=0;a[i]!=-99;i++)
if(a[i]==t)
break;
for(j=0;j<i;j++)
if(a[j]==key)
return 1;
return 0;
}
void inorder(node *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%6d",root->data);
inorder(root->right);
}}
void preorder(node *root)
{ if(root!=NULL)
{
printf("%6d",root->data);
preorder(root->left);
preorder(root->right);
}
}

Data Structures Using C


Trees ADT

5.9. BINARY SEARCH TREE ADT (BST)


A binary search tree is a special binary tree. It should satisfy the following
characteristics,
1. Every node has a value and no two nodes have the same value (i.e. the values in the
binary search tree are unique).
2. The values in the left subtree are less than the value of its parent node.
3. The values in the right subtree are greater than the value of its parent node.
4. The left and right sub trees of each node are again the binary search tree.
For example,

BASIC OPERATIONS OF BINARY SEARCH TREE


1. Creation of binary search tree from a series of elements
2. Insertion of a node
3. Deletion of a node
4. Searching a node
5. Modification of a node
6. View the elements of the BST or Traversal of BST
5.9.1. REPRESENTATION OF BINARY SEARCH TREE
Linked list data structure is a best way to implement the binary search tree, because
insertion and dilation operation done by changing the link fields of a node without
interchanging the nodes. It also uses the allotted memory space efficiently.
NODE STRUCTURE

1. Creation of a BST
Creation of BST involves 3 processes.
1. Each node is a structure with 3 members. The memory is allocated for a node
dynamically using malloc( ) library function.
2. Create a node and assign NULL to the link field of newnode.
3. Read data for the newnode from user and store it in data field.
4. The creation of BST is done by repeatedly calling the insertion operation of BST.
2. Insertion of a node

Data Structures Using C


Trees ADT

One of the most primitive operations that can be done in a binary search tree is
insertion. The procedure for inserting a newnode in the existing binary search tree becomes,
Algorithm
1. Create a node by using malloc( ) and NULL to the link field of node. Get the
data from the user and assign it in data field of node.
2. Check whether the root node of BST is NULL or not.
3. If it is NULL, then consider the new node as the root node of BST. Otherwise
do next.
4. Compare the root node data with new node data for the following three
conditions.
a) If the content of data is equal to the root node data, then insertion
operation is terminated due to duplication of data.
b) If the content of the new node data is less than the root node data, then
check whether the left child of root node is NULL. If it is NULL then
insert the new node as the left child of root node (i.e. Root->
left=newnode). Otherwise consider the left child of root node become a
root node and repeat the process from step-4.
c) If the content of the new node data is greater than the root node data,
then check whether the right child of root node is NULL. If it is NULL
then insert the new node as the right child of root node (i.e. Root->
right=newnode). Otherwise consider the right child of root node
become a root node and repeat the process from step-4.
For example, create a BST for the following elements {7, 5, 10, 3, 6, 9, and 8}. Initially
BST is not yet created i.e. Root== NULL. So the first element 7 becomes the root node.

Data Structures Using C


Trees ADT

Pseudo Code
Tree-Insert (T, z)
y = NIL
x = root[T]
While x != NULL
do y = x
if key[z] < key[x] then
x = left[x]
else
x = right[x]

P[z] = y
if y = = NULL then
root[T] = z
else if key[z] < key[y] then
left[y] = z
else
right[y] = z

3. Deletion of a node
Another primitive operation that can be done in a BST is the deletion of a node. A
node can be deleted from the tree in 3 different places.
a) Deleting the leaf node
b) Deleting the node with only one child
c) Deleting the node with two children
a) Deleting the leaf node
Algorithm
Step-1: Search the parent node of the leaf node (which is going to be deleted) and
assign NULL to the link field of the leaf node.
Step-2: Release the memory for the deleted node by using free ( ) function.

Data Structures Using C


Trees ADT

b) Deleting the node with only one child


Algorithm
Step-1: Search the parent node of the deleted node which has one child (going to
be deleted).
Step-2: Assign the child node address of the deleted node to the parent node link
field of the deleted node.
Step-3: Release the memory for the deleted node by using free () function.

c) Deleting the node with two children


Algorithm
Step-1: Search the parent of the node to be deleted.
Step-2: Copy the value of in order successor to the node to be deleted.
Step-3: If the in order successor node has only one child, delete the node by
calling “Delete with one child”. If the in order successor node has no child,
delete the node by calling “Delete leaf node method”.
Step-4: Release the memory for in order successor node.
Step-5: Finally assign the (deleted in order successor node value) copied
node value to the node to be deleted.

Data Structures Using C


Trees ADT

Pseudo Code
Tree-Delete (T, z)
if left[z] = = NULL or right[z] = = NULL then
y=z
else
y = Tree-Successor(z)
if left[y] != NULL then
x = left[y]
else
x = right[y]
if x != NULL then
P[x] = P[y]
if P[y] = = NULL then
root[T] = x
else if y = left[P[y]] then
left[P[y]] = x
else
right[P[y]] = x
if y != z then
key[z] = key[y]
copy y’s data into z
return y

Data Structures Using C


Trees ADT

4. Searching an element in BST


Algorithm
1) Check whether the root node is NULL. If yes print “binary search tree is empty” and
terminate the process. Otherwise do next.
2) Compare the root node data with the search node for the following 3 conditions.
i. If the data of the root is equal to the search node then print “Data found”
and terminate the process.
ii. If the search data is less than the root data, check whether the root->left is
NULL or not. If NULL print “search not found” and terminate the process.
Otherwise, consider the left child becomes the root and do again from 2nd
step.
iii. If the search data is greater than that of the root data, then check whether
the root->right is NULL or not. If NULL print “search data not found” and
terminate the process. Otherwise, consider the right child becomes the root
and do again from 2nd step.

Pseudo Code
Tree-Search(x, k)
if x = = NULL or k = key[x] then
return x
if k < key[x] then
return Tree-Search(left[x], k)
else
return Tree-Search(right[x], k)

5. Modification of an element in BST


Algorithm
Step-1: First search the node to be modified by using searching operation.
Step-2: Get the value from the user and compare the value is lesser than the parent (if
search value is a left child), otherwise compare the value is greater than the parent (if
search value is a right child).
Step-3: If the condition fails terminate the process.

6. To find minimum and maximum element in BST


Pseudo Code
Tree-Minimum(x)
while left[x] != NULL
do x = left[x]
return x
Tree-Maximum(x)
while right[x] != NULL
do x = right[x]

Data Structures Using C


Trees ADT

return x

7. To find the successor of a given node in BST


Pseudo Code
Tree-Successor(x)
if right[x] != NULL then
return Tree-Minimum(right[x])
y = P[x]
while y != NULL and x = = right[y]
do x = y
y = P[y]
return y

IMPLEMENTATION IN C
/* Binary Serach Tree ADT */

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

#define p printf
#define s scanf
typedef struct node
{
int data;
struct node *left,*right;
}tree;

tree *getnode( );
void readnode(tree *);
tree *create( );
void view(tree *btree, int level);
tree *insertnode(tree *btree, tree *temp);
void main( )
{
int choice;
tree *btree=NULL,*temp;
clrscr();
while(1)
{
p("\n1.create\n2.Display\nEnter u'r choice\n");
s("%d",&choice);

Data Structures Using C


Trees ADT

switch(choice)
{
case 1:
btree=NULL;
p("\ncreate a new tree\n");
btree=create();
break;
case 2:
if(btree!=NULL)
{
p("Binary tree is\n");
view(btree,1);
}
else
p("Tree is Empty\n");
break;
case 3:
exit(0);
break;
default:
break;
}
}
}
tree *getnode()
{
tree *newnode;
newnode=(tree *)malloc(sizeof(tree));
return newnode;
}
void readnode(tree *newnode)
{
p("Enter the Value\n");
s("%d",&newnode->data);
newnode->left=NULL;
newnode->right=NULL;
}
tree *create()
{
int ch=1;
tree *btree=NULL,*temp;
while(ch==1)
{

Data Structures Using C


Trees ADT

temp=getnode();
readnode(temp);
btree=insertnode(btree,temp);
p("2 u wish 2 continue press 1\n");
scanf("%d",&ch);
}
return btree;
}
tree *insertnode(tree *btree,tree *temp)
{
if(btree==NULL)
{
return temp;
}
else if(temp->data<btree->data)
{
btree->left=insertnode(btree->left,temp);
}
else if(temp->data>btree->data)
{
btree->right=insertnode(btree->right,temp);
}
else if(temp->data==btree->data)
{
p("\n data is alreaty exit\n");
return btree;
}
return btree;
}
void view(tree *btree, int level)
{
int k;
if(btree==NULL)
return;
view(btree->right,level+1);
p("\n");
for(k=0;k<level;k++)
p(" ");
p("%d",btree->data);
view(btree->left,level+1);
}

Sample I/O

Data Structures Using C


Trees ADT

1.create
2.Display
Enter u'r choice 1
create a new tree
Enter the Value 20
2 u wish 2 continue press 1 1
Enter the Value 10
2 u wish 2 continue press 1 1
Enter the Value 30
2 u wish 2 continue press 1 1
Enter the Value 5
2 u wish 2 continue press 1 1
Enter the Value 15
2 u wish 2 continue press 1 1
Enter the Value 25
2 u wish 2 continue press 1 1
Enter the Value 35
2 u wish 2 continue press 1 1
Enter the Value 40
2 u wish 2 continue press 1 2
1.create
2.Display
Enter u'r choice 2
Binary tree is

40
35
30
25
20
15
10
5

5.10. THREADED BINARY TREE


For ‘N’ node binary tree which is implemented by using the linked list data
structure, have “N+1” Null pointers. Nearly half of the memory spaces are wasted or not
utilized for important purpose, only just for keeping the NULL values.

Need or Use of Threaded Binary tree


♣ To overcome this (i.e.) for the effective use of those NULL spaces, a threaded
binary tree is used.

Data Structures Using C


Trees ADT

♣ In a threaded binary tree only two NULL pointers is used to indicate the start and
end pointer of binary tree where these nodes are first & last values in the Inorder
traversal of tree.
♣ It is also possible to discover the parent of a node, without explicit use of parent
pointer or a stack
♣ Threaded binary tree leads a more rapid linear traversal of binary tree rather than the
recursive traversal (i.e. during the traversal process, if it reaches the leaf node then it
should backtrack to its parent node and start the traversal process in different path.
So the traversal operations are performed only by making recursive functions. This
will be avoided when a binary tree is converted into a threaded binary tree).

Definition
A binary tree is threaded by making the entire right child pointers which has NULL
become points to the inorder successor of that node and all left child pointers which has
NULL would points to the inorder predecessor of that node. These valued are called as
Threads.
♣ If a node is a left child then its right link points to its parent or its right child.
♣ If a node is a right child then its left link points to its parent or its left child.
Example:

For the above binary tree, the Inorder traversal is [A, B, C, D, E, F, G, H, I]. Leaves
are A, C, E and H. A node which has NULL to its link field is {A, C, E, G, I, and H}
In threaded binary tree, Left Child of ‘A’ becomes NULL to indicate that A is a
starting node in Inorder traversal. Right Child of ‘I’ becomes NULL to indicate that I is an
end node in inorder traversal. Dashed edges indicate the threads.
✔ A is left child, so its right link points to its parent ‘B’.
✔ C is left child, so its right link points to its parent ‘D’.
✔ E is right child, so its left link points to its parent ‘D’.

Linear Traversal Procedure (with the help of threads)


Step-1: Start with a node which has NULL pointer to its left link (i.e. A)

Data Structures Using C


Trees ADT

Step-2: Process/ visit the node and say it as ‘N’.


Step-3: Until right child of ’N’ is not NULL do the following steps.
⮚ Find right child of N and mark it as ‘M’.
⮚ If (left child of M is==N (or) left child of M is already in the visited node
list) then visit M and mark it as N now
⮚ Else assign M as M->left child.
For example, consider the following threaded binary tree to perform the inorder traversal
without backtracking of edges or without using recursive function call.

Inorder Traversal for the above threaded binary tree is {1, 2, 3, 4, 5, 6, 7, 8, and
9} Initially N=1 and Visit-List = {1}. Further passes are,

⮚ N=1, M=2(right child of N),


✔ Left child of ‘M’ is ‘1’==N
✔ So Visit-List={1, 2}
✔ N=M (i.e.) N=2.
⮚ N=2, M=3(right child of N)
✔ Left child of ‘M’ is ‘2’==N
✔ So Visit-List={1, 2, 3}
✔ N=M (i.e.)N=3
⮚ N=3, M=4
✔ Left child of ’M’ is 2 (i.e.) Already visited
✔ So Visit-List={1, 2, 3, 4}
⮚ N=4, M=5
✔ So Visit-List={1, 2, 3, 4, 5}
⮚ N=5, M=6
✔ So Visit-List={1, 2, 3, 4, 5, 6}
⮚ N=6, M=8
✔ Left child of ‘M’ is 7!= N and not visited
✔ So M become M->left (i.e.) 7
✔ M=7 Left child of M is 6==N

Data Structures Using C


Trees ADT

✔ So Visit-List={1, 2, 3, 4, 5, 6, 7}

⮚ Follow the above procedure for when N=7, 8 & 9.

BALANCED TREES ADT


6.1. AVL TREES
We know that the height of the tree is the length of the longest path from the root to
a leaf. A binary search tree is called as a height balanced k-tree (or) HB[k] tree, if each
node in the tree has the HB[k] property. A node is said to have the HB[k] property, if the
height of the left and right subtrees of a node differ in height by at most ’k’. AVL tree has
HB[1] property. AVL trees were named after the Russian Mathematicians Adelson’s,
Velskii and Landis, who first defined HB[k] trees.

NEED FOR AVL TREES


Even though the BST needs a less execution time for insertion and deletion, the
search operation is based on the number of levels or height of the BST. If a BST is left or
right skewed then the total elements are in either left subtree or right subtree respectively.
So the search time leads to O(N) rather than O(log N) where N indicates the number
of elements in tree. Therefore, the BST is act like a linear list when it is right or left
skewed. To avoid this, we could use AVL tree which maintains the balance height of BST.
So it requires only O(log N) time to search an element from the AVL tree.

DEFINITION
AVL tree is also referred as Self-Adjusting binary search tree. It is a binary search
tree that satisfies the HB[1] property i.e. the heights of the left and right sub trees of a node
should differ by at most 1. For maintaining the HB[1] property, it keeps an addition piece of
information at each node referred as a “Balance Factor” which is denoted as BF(N) where
N is a node.

Data Structures Using C


Trees ADT

♣ Balance factor of a node is calculated by the difference between the height of its left
sub tree and the height of its right sub tree.

♣ In AVL trees, each node N should have a Balance Factor BF(N) either {-1, 0 or +1}.
AVL tree is called as a height balanced tree which means, it can be built to maintain
the balance within the left as well as its right subtrees.
♣ Any insertion or deletion of a node in AVL tree may violate the property of it (i.e.)
Balance Factor of any node should be greater than one. So, after each insertion or
deletion process the tree will be analyzed to see whether it violates the balance
condition or not. If it violates, then we need to reorganize the tree by a series of
“Rotations” to make it again balanced.
♣ Thus the insertion and deletion methods should be sensitive to maintaining this
balance factor of all nodes in AVL tree. The height of an AVL tree with N nodes
never exceeds (1.44 log N) and is typically much closer to log N.
♣ In N node - AVL tree, a node can be searched within O(log N) time. Insertion and
deletion operations in AVL tree can also be performed in O(log N) time.

For example,

From the above AVL tree {A, B, C, D, E, F, G, H, I, J and K} are elements and the
number represented in each node specifies the balance factor of that node. For example
BF(A)=0, BF(B)=1, BF(C)=0, BF(D)=(-1)

6.1.1. BASIC OPERATIONS OF AVL TREE


1. Creation of AVL tree
2. Insertion of a node
3. Deletion of a node
4. Searching a node
5. Modification of a node
6. View the elements of AVL tree
AVL tree is a BST. So the operations are same as Binary search tree which is
discussed in the previous chapter. Some additional process such as Rotation will be carried
out in insertion and deletion process compare to the binary search tree, since the nodes are

Data Structures Using C


Trees ADT

balanced or unbalanced after insertion or deletion of a node from tree. So depending upon
the balance factor of a node the rotation will be performed on the tree.

In case of insertion, one rotation is sufficient but in case of deletion O(logN)


rotations at most are needed.
Note:
6.1.2. ROTATIONS & TYPES
In an AVL tree, during insertion or deletion of a node, the nodes in the path from the
insertion/deletion point to the root may become unbalanced. In such cases, the structure of
the tree should be slightly modified to restore the balance of the nodes. Such modification
of the structure is called ROTATION.
A node become unbalanced, only if its left or right subtree grows longer than its
right or left subtree by 2 levels (i.e.) BF(N) >1. Rotation tries to make BF(N) becomes
either {0, -1, 1} which shorten the subtree that has grown longer.
There are 4 types of rotations used in rebalancing an AVL trees.
1. Single left Rotation (SLR) or L-L Rotation.
2. Single right Rotation (SRR) or R-R Rotation.
3. Double left Rotation (DLR) or L-R Rotation. (R - Inner rotation & L – Outer
rotation)
4. Double right Rotation (DLR) or R-L Rotation. (L - Inner rotation & R – Outer
rotation)
♣ Inserting a node on the outside of the tree (i.e.) in the left side of left most
subtree or in the right side of right most subtree. These unbalance of node can be
fixed by Single Rotation.
♣ Inserting a node on the inside of left or right of subtrees. The unbalance caused
by such insertions can be fixed by Double rotation.

SINGLE ROTATION

Data Structures Using C


Trees ADT

DOUBLE ROTATION

Data Structures Using C


Trees ADT

6.1.3. INSERTION OF A NODE


Step-1: Do the insertion procedure in binary search tree (Refer previous chapter)
Step-2: Mark the insertion path from the inserted node to root then calculate the
Balance factor for a node in the insertion path only from the inserted position to
root.
Step-3: If all the node has balance factor either {0 or 1 or -1}, then terminate the
process. (i.e.) It’s an AVL tree even after the insertion.
Step-4: Otherwise, if a node has a balance factor either {-2 or +2} then mark that node
as Pivot node and stop the calculation of balance factor for other nodes in inserted
path after the pivot node.

Data Structures Using C


Trees ADT

Step-5: Identify the type of rotation which is performed to recover the AVL property
of a tree by traverse the insertion path only 2 steps downward from the pivot node.
(i.e.) visit only 2 nodes from the pivot node.
a) If the first node is a left child of pivot node say ‘K’ and second node is a left
child of Kth node then we have to perform L-L rotation.
b) If the first node is a right child of pivot node say ‘K’ and second node is a
right child of Kth node then we have to perform R-R rotation.
c) If the first node is a left child of pivot node say ‘K’ and second node is a
right child of Kth node then we have to perform L-R rotation.
d) If the first node is a right child of pivot node say ‘K’ and second node is a
left child of Kth node then we have to perform R-L rotation.
Step-6: Perform the corresponding rotation to recover a balanced tree which satisfies
the AVL Property.
No need to calculate the balance factor of nodes in AVL tree after performing the
rotation process. Surely it will satisfy the property of Binary search tree and
become balanced after a single or double rotation performed on an unbalanced
Note: tree.

For example, Consider the following sequence of elements 3, 2, 1, 4, 5, 6, 7, 16, 15 and 14


to form AVL tree.

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

IMPLEMENTATION IN C
typedef struct AVLNode *AVLTree, *Position;
struct AVLNode
{
int data;
AVLTree Left, Right;
int height;
}
static int Height(Position p)
{
if(P= =NULL) return -1;
else return P->height;
}

Data Structures Using C


Trees ADT

Insert(x, T)
{
if(T= = NULL)
{
T = malloc (size of (struct AVLNode) );
T -> data = h;
T-> height = 0;
T-> Left = T-> Right = NULL;
}
else if (x < T->data)
{
T-> Left = Insert(X, T->left);
if(height(T->Left) – height(T->Right) = = 2)
if(x < T->Left->data)
T = SingleRotateWithLeft( T );
else
T = DoubleRotateWithLeft( T );
}
else if(x > T->data)
{
T-> Right = Insert(X, T-> Right);
if(height(T-> Right) – height(T-> Left) = = 2)
if(x > T-> Right ->data)
T = SingleRotateWithRight( T );
else
T = DoubleRotateWithRight( T );
}
T->height = Max(height(T->Left), height(T->Right) ) + 1;
return T;
}
static Position SingleRotateWithLeft(Position K2)
{
Position K1;
K1 = K2->Left;
K2->Left = K1->Right;
K1->Right = K2;
K2->height = Max(Height(K2->Left), Height(K2->Right)) + 1;
K1->height = Max(Height(K1->Left), Height(K2->Right)) + 1;
return K1;
}
static Position SingleRotateWithRight(Position K2)
{
Position K1;

Data Structures Using C


Trees ADT

K1 = K2->Right;
K2->Right= K1->Left;
K1->Left = K2;
K2->height = Max(Height(K2->Right), Height(K2-> Left)) + 1;
K1->height = Max(Height(K1->Right), Height(K2-> Left)) + 1;
return K1;
}
static Position DoubleRotateWithLeft(Position K3)
{
K3->Left = SingleRotateWithRight(K3->Left);
return SingleRotateWithLeft(K3);
}
static Position DoubleRotateWithRight(Position K3)
{
K3->Right = SingleRotateWithLeft(K3-> Right);
return SingleRotateWithRight (K3);
}

6.1.4. DELETION OF A NODE


It involves 3 steps,
1. Search the tree and delete the node, similar to binary search tree.
2. Check whether the tree becomes balanced or not by calculating BF for all nodes. If
any node has a BF {>1 or < -1} then it is not an AVL tree.
3. Apply an appropriate rotation to retain the AVL tree.

An insertion into an AVL tree requires one single or double rotation to retain the
balance property of AVL tree. However deletion requires at most (logN) rotation, because
deletion of a node causes unbalance in the opposite subtree of the deleted node.
Rotation should be performed from the first node which causes unbalance on tree
and then moving upward to the root of the tree. Experimentally, it has been found that 50%
of insertion operations do not require rotation process or rebalancing but 75% of deletion
oprations do not require rebalancing.

For example, consider the following AVL tree to perform deletion.

Data Structures Using C


Trees ADT

6.2. BINARY HEAP


Heap is an almost complete binary tree. In almost complete binary every non-leaf
node has less than or equal to two children and leaf nodes are not necessarily to be on the
same level of tree. The leaves should be in either the level (h-1) or level (h-2), where h is a
height of binary tree. Binary heap has two properties,
1. Structure Property
The elements are inserted in level by level from leftmost to rightmost. (i.e.)
after the insertion of left child to the node, the right child can be inserted and
also nodes are not inserted intermediately which should be from leftmost to
rightmost.
2. Ordered Property
Heap must be either in Max-Heap or Min-Heap structure.
Max-Heap: Each node has key or data that must be greater than its key of
children.
Min-Heap: Each node has key or data that must be lesser than its key of
children.

For example,

Data Structures Using C


Trees ADT

6.2.1. REPRESENTATION OF HEAP


Since heaps are almost a complete binary tree so array representation will be
efficient (as there will be no empty subtree in the intermediate levels due to its structure
property). Recall that, in array representation the left child of node P is inserted at 2ith index
of array, right child of node P is inserted at (2i+1)th index of array and parent of node P is
in the index of (i/2) where ‘i’ is greater than 1.

PSEUDO CODE
Parent(i)
{
return (i/2)
}

Left(i)
{
return (2i)
}

Right(i)
{
return (2i+1)
}

Data Structures Using C


Trees ADT

6.2.2. OPERATIONS ON A HEAP


1. Build a Max or Min Heap
2. Insertion
3. Extract the Maximum or Minimum element.
4. Deletion
The primitive operations on a heap are insertion and deletion. After the operations
of insertion and deletion, a tree should be readjusted to satisfy the heap properties. The
process of this readjusting is referred as Heapify process.

1. BUILD A MAX OR MIN HEAP


This operation is used to construct a Max-heap or Min-heap from a series of input
elements. The following algorithm creates a Max-heap.
In Min-Heap compare the key of X is lesser than its children instead of comparing
the key of X is greater than its children.

ALGORITHM
Step-1: Allocate the size of array by 2H where H represents the height of the tree.
Step-2: Sequentially insert the input elements onto the array of HeapSize, only after
incrementing HeapSize by 1. HeapSize refers the number of nodes in heap tree and
initially it is 0.
Step-3: Take an index (HeapSize/2) & say ‘X’ where X is the index of first parent node
in rightmost place of highest level in tree.
Step-4: Call to Heapify process by passing X.
Step-5: Decrement X by one and repeat from step 4 until X is equal to 1 (i.e.) root node

HEAPIFY ALGORITHM
Step-1: Compare the key of index X with its key of left and right child, if the key of X is
greater than the children then terminate the process (i.e.) already the tree satisfy the
heap properties.
Step-2: If any one of the child has greater key than key of X then take the index of
largest key say ‘L’.
Step-3: If L is not equal to X then exchange the key of L and X as well as assign L to X
and Repeat the steps from 4 until X has no child.

PSEUDO CODE
Build-Max-Heap (A)
HeapSize[A] = length[A]
for i=floor(length(A/2)) downto 1 // floor returns the integer part of float i.e. the value
before ‘.’
do Max-Heapify(A, i)

Build-Min-Heap (A)
HeapSize[A] = length[A]

Data Structures Using C


Trees ADT

for i=floor(length(A/2)) downto 1


do Min-Heapify(A, i)

Max-Heapify(A, i)
L=Left(i)
R=Right(i);
if L <= HeapSize[A] and A[L] > A[i] then
largest = L
else
largest = i
if R <= HeapSize[A] and A[R] > A[largest] then
largest = R
if largest != i then
Exchange A[i], A[largest]
Max-Heapify(A, largest)

Min-Heapify(A, i)
L=Left(i)
R=Right(i);
if L <= HeapSize[A] and A[L] < A[i] then
smallest = L
else
smallest = i
if R <= HeapSize[A] and A[R] < A[smallest] then
smallest = R
if smallest!= i then
Exchange A[i], A[smallest]
Min-Heapify(A, smallest)

For example, consider the input sequence {7, 15, 8, 12 and 20} to build a Max-heap with
the height of 3.
Step 1: form a tree for the given input sequence.

Step 2: Calculate Position X = Floor(HeapSize/2) (i.e.) Floor(5/2) =Floor(2.5) =2

Data Structures Using C


Trees ADT

When X = 1

INSERT A NODE ON HEAP


The following algorithm Insert a node onto the Max-heap. In Min-Heap compare the
key of I is lesser than its children instead of comparing the key of I is greater than its
children.
ALGORITHM
Step-1: Increment the HeapSize by one and Read the data to insert.
Step-2: Assign the data to the array of HeapSize
Step-3: Say the index of newly inserted element as ‘I’
Step-4: If the key of I is less than key of its Parent then terminate the process otherwise
do next.
Step-5: If the key of I is greater than key of its Parent then exchange the key of I and
Parent.
Step-6: Assign index of Parent to I
Step-7: Repeat from Step 4 until I becomes 1.

PSEUDO CODE
Max-Heap-Insert(A, key)
HeapSize = HeapSize + 1
A[HeapSize] = key
I = HeapSize
while I >1 and A[Parent(I)] < A[I]
do exchange A[Parent(I)], A[I]

Data Structures Using C


Trees ADT

I = Parent(I)

Min-Heap-Insert(A, key)
HeapSize = HeapSize + 1
A[HeapSize] = key
I = HeapSize
while I >1 and A[Parent(I)] > A[I]
do exchange A[Parent(I)], A[I]
I = Parent(I)

For example, insert an element 25 onto the following heap tree

2. EXTRACT MINIMUM OR MAXIMUM ELEMENT


This operation is used to delete a maximum element from the Max-Heap or
delete a minimum element from the Min-Heap. Always the element going to be extracted is
a root node. After deleting a node from heap, it should be Heapify to retain the property of
heap.

ALGORITHM
Step-1: Check the HeapSize is less than one or not. If it is less than one then show error
message as “Heap underflow” and terminate the process
Step-2: Otherwise, assign the array of first element as Max (or Min for minimum
element) and assign key of HeapSize to the key of first element.
Step-3: Decrease the HeapSize by one and make a call to Max-Heapify(A, 1) or
Min-Heapify(A, 1)
Step-4: Return the Max (or Min) is an Extracted node from a heap.

PSEUDO CODE
Heap-Extract-Max(A)

Data Structures Using C


Trees ADT

if HeapSize < 1 then


Error “Heap Underflow”
Max = A[1]
A[1] = A[HeapSize]
HeapSize = HeapSize – 1
Max-Heapify(A, 1)
return Max

Heap-Extract-Min(A)
if HeapSize < 1 then
Error “Heap Underflow”
Min = A[1]
A[1] = A[HeapSize]
HeapSize = HeapSize – 1
Min-Heapify(A, 1)
return Min

For example, extract the maximum element from the following Max-Heap

3. DELETE A NODE FROM A HEAP


This operation is used to delete any element from the Max-Heap or Min-Heap.
After deleting a node from heap, it should be Heapify to retain the property of heap. The
following algorithm is for deleting an element from Max-Heap. In Min-Heap compare the
key of I is lesser than its children instead of comparing the key of I is greater than its
children.
ALGORITHM
Step-1: Consider D is an index of node which is going to be deleted.
Step-2: Assign the key of D as key of (array[1]) + 1.
Step-3: Exchange the key of D with a key of its Parent.
Step-4: Assign index of Parent to D
Step-5: Repeat from Step from 3 until D becomes 1.
Step-6: If it is a Max-Heap then call Heap-Extract-Max(A) else call
Heap-Extract-Min(A)

PSEUDO CODE

Data Structures Using C


Trees ADT

MaxHeap-Delete-Node(A, D)
A[D] = A[1] + 1
while (D < 1)
Exchange A[Parent(D)], A[D]
D = Parent(D)
Heap-Extract-Max(A)
MinHeap-Delete-Node(A, D)
A[D] = A[1] + 1
while (D < 1)
Exchange A[Parent(D)], A[D]
D = Parent(D)
Heap-Extract-Min(A)
For example, delete an element 15 from the following heap tree

6.2.3. APPLICATIONS OF BINARY HEAP


1. Heap Sort
2. Priority Queue

1. HEAP SORT
This is a one type of sorting technique which requires a less execution time
compare to Insertion sort & Selection sort techniques. The best, average and worst case
running time to perform sorting is O(Log N) where N is a number of elements to sort.

PSEUDO CODE
HeapSort-Descending(A)
Build-Max-Heap(A)
i = length[A]
while i <= 2
do Exchange A[i], A[1]

Data Structures Using C


Trees ADT

HeapSize = HeapSize – 1
Max-Heapify(A, 1)

HeapSort-Ascending(A)
Build-Min-Heap(A)
i = length[A]
while i <= 2
do Exchange A[i], A[1]
HeapSize = HeapSize – 1
Min-Heapify(A, 1)

2. PRIORITY QUEUE
It is a type of Queue ADT. The operations of priority queue are insertion and deletion
which is worked based on the priority of each element. Implementation of priority queue is
done by the heap representation which takes O(Log N) time to execute insertion or
deletion.

1. Ascending priority queue – elements can be inserted arbitrarily but an element


with small priority will be deleted first from the queue.
♣ It is implemented by Min-Heap
♣ Insertion of a node on priority queue is done in the same way of inserting a
node onto Min-heap.
♣ Deletion of a node from the priority queue is done by Heap-Extract-Min.

2. Descending priority queue - elements can be inserted arbitrarily but an element


with large priority will be deleted first from the queue.
♣ It is implemented by Max -Heap
♣ Insertion of a node on priority queue is done in the same way of inserting a
node onto Max-heap.
♣ Deletion of a node from the priority queue is done by Heap-Extract- Max.

B - Trees

In a binary search tree, AVL Tree, Red-Black tree etc., every node can have only one value
(key) and maximum of two children but there is another type of search tree called B-Tree in
which a node can store more than one value (key) and it can have more than two children.
B-Tree was developed in the year of 1972 by Bayer and McCreight with the name Height
Balanced m-way Search Tree. Later it was named as B-Tree.

B-Tree can be defined as follows...

Data Structures Using C


Trees ADT

B-Tree is a self-balanced search tree with multiple keys in every node and more than
two children for every node.

Here, number of keys in a node and number of children for a node is depend on the order of
the B-Tree. Every B-Tree has order.

B-Tree of Order m has the following properties...


● Property #1 - All the leaf nodes must be at same level.
● Property #2 - All nodes except root must have at least [m/2]-1 keys and maximum
of m-1 keys.
● Property #3 - All non leaf nodes except root (i.e. all internal nodes) must have at
least m/2 children.
● Property #4 - If the root node is a non leaf node, then it must have at least
2 children.
● Property #5 - A non leaf node with n-1 keys must have n number of children.
● Property #6 - All the key values within a node must be in Ascending Order.

For example, B-Tree of Order 4 contains maximum 3 key values in a node and maximum 4
children for a node.

Example

OThe following operations are performed on a B-Tree...


1. Search
2. Insertion
3. Deletion

Search Operation in B-Tree


In a B-Ttree, the search operation is similar to that of Binary Search Tree. In a Binary
search tree, the search process starts from the root node and every time we make a 2-way
decision (we go to either left subtree or right subtree). In B-Tree also search process starts
from the root node but every time we make n-way decision where n is the total number of

Data Structures Using C


Trees ADT

children that node has. In a B-Ttree, the search operation is performed with O(log n) time
complexity. The search operation is performed as follows...

● Step 1: Read the search element from the user


● Step 2: Compare, the search element with first key value of root node in the tree.
● Step 3: If both are matching, then display "Given node found!!!" and terminate the
function
● Step 4: If both are not matching, then check whether search element is smaller or
larger than that key value.
● Step 5: If search element is smaller, then continue the search process in left subtree.
● Step 6: If search element is larger, then compare with next key value in the same
node and repeate step 3, 4, 5 and 6 until we found exact match or comparision
completed with last key value in a leaf node.
● Step 7: If we completed with last key value in a leaf node, then display "Element is
not found" and terminate the function.

Insertion Operation in B-Tree


In a B-Tree, the new element must be added only at leaf node. That means, always the new
keyValue is attached to leaf node only. The insertion operation is performed as follows...

● Step 1: Check whether tree is Empty.


● Step 2: If tree is Empty, then create a new node with new key value and insert into
the tree as a root node.
● Step 3: If tree is Not Empty, then find a leaf node to which the new key value cab
be added using Binary Search Tree logic.
● Step 4: If that leaf node has an empty position, then add the new key value to that
leaf node by maintaining ascending order of key value within the node.
● Step 5: If that leaf node is already full, then split that leaf node by sending middle
value to its parent node. Repeat tha same until sending value is fixed into a node.
● Step 6: If the spilting is occuring to the root node, then the middle value becomes
new root node for the tree and the height of the tree is increased by one.

Example
Construct a B-Tree of Order 3 by inserting numbers from 1 to 10.

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C


Trees ADT

Data Structures Using C

You might also like