SlideShare a Scribd company logo
1 of 70
Unit V: Tree
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
Tree Data Structure - Definition
Tree is an example for a non linear data structure
where nodes(elements) exhibit hierarchical relationship
among them. As it is non linear in nature nodes can
exist at random memory locations.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Tree - Terminologies
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Root Node
Root node is the node which exist at the top of the Tree in Level zero.
Every Tree data structure should have one and only one Root Node.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Edge
The connecting link between any two nodes(elements) of the tree is
defined as an Edge.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Parent Node
The node which has a branch from it to any other node is called
as a parent node. In other words, a node which has one or
more children is defined as a parent node. In a general Tree
data structure a parent can have any number of children.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here,
•Node A is the parent of nodes B and C
•Node B is the parent of nodes D, E and F
•Node C is the parent of nodes G and H
•Node E is the parent of nodes I and J
•Node G is the parent of node K
Child Node
A node which is a descendant of some node is defined as a child node.
All nodes except the Root node are child nodes.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here,
•Nodes B and C are the children of node
A
•Nodes D, E and F are the children of
node B
•Nodes G and H are the children of node
C
•Nodes I and J are the children of node
E
•Node K is the child of node G
Siblings
Child nodes of the same parent are called siblings
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here,
•Nodes B and C are siblings
•Nodes D, E and F are siblings
•Nodes G and H are siblings
•Nodes I and J are siblings
Degree of a Node
Degree of a node is the total number of children of the node.
Degree of a Tree is the highest degree of the node among all the nodes
of the Tree.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here,
•Degree of node A = 2
•Degree of node B = 3
•Degree of node C = 2
•Degree of node D = 0
•Degree of node E = 2
•Degree of node F = 0
•Degree of node G = 1
•Degree of node H = 0
•Degree of node I = 0
•Degree of node J = 0
•Degree of node K = 0
Internal(Non-Terminal / Non-Leaf) Node
The node which has at least one child is defined as Internal or Non
Terminal or Non Leaf node.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here, nodes A, B, C, E and G are internal
nodes.
Leaf Node (Terminal Node or External Node)
A node which does not have any child is defined as a Leaf Node.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here, nodes D, I, J, F, K and H are leaf nodes.
Level
In a Tree each step from top to bottom is defined as a level of the Tree.
Root Node is existing at Level Zero and level number increases by unity
as we go down the Tree.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Height or Depth of a Tree
Height or Depth of a Tree is the maximum number of nodes in the
longest branch of the Tree. It is usually one more than the largest level
number.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Subtree
In a tree, each child from a node forms a subtree recursively.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Forest
A forest is a set of disjoint trees.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Binary Trees
A tree where every node can have maximum two children(zero child,
one child or two children) is defined as binary tree.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
parent
left child right child
Maximum No. of nodes possible
in a level of binary tree
Maximum number of nodes possible in a level of binary tree is 2Level No.
In Level Zero Maximum No. of nodes possible is 1 (Only Root Node available in Level Zero)
In Level One Maximum No. of nodes possible is 2
In Level Two Maximum No. of nodes possible is 4
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Memory Representation of Binary
Tree
Binary Tree can be represented in the memory in two ways:
1. Array Representation
2. Linked Representation
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Array Representation of Binary Tree
In the array representation of binary tree the array indices are assumed
to begin from 1st index and the root node is stored in the 1st index of
the array.
If L denote the index where a node is stored in the array then its left
child will be stored in (2 * L)th index of the array and its right child will
be stored in (2 * L + 1)th index of the array.
If a left or right child does not exist for a node then the corresponding index location in the array is left
blank.
If L denote the index in the array where a node is stored then its parent will be stored in ( L / 2 )th index of
the array.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Binary Tree Array Representation with Index
of Array
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Linked Representation of Binary Tree
In linked and dynamic representation each node constitutes of a
data part and two link parts. The two link parts store address of
left and right child nodes. Data part is used to store the
information.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Definition of a node in linked representation of
Binary Tree
struct n
{
struct n *left;
int info;
struct n *right;
};
typedef struct n node;
node *ROOT = NULL;
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Traversal of Nodes in Binary Tree
Traversal is a process to visit all the nodes of a tree and may
print their values too. Because, all nodes are connected via
edges (links) we always start from the root (head) node. That is,
we cannot randomly access a node in a tree. There are three
ways which we use to traverse a tree −
• Inorder Traversal
• Preorder Traversal
• Postorder Traversal
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Inorder Traversal Algorithm
Step 1: Traverse the left subtree of the Root Node R in inorder
Step 2: Process the Root node R
Step 3: Traverse the right subtree of the Root Node R in inorder
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Preorder Traversal Algorithm
Step 1: Process the Root node R
Step 2: Traverse the left subtree of the Root Node R in preorder
Step 3: Traverse the right subtree of the Root Node R in preorder
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Postorder Traversl Algorithm
Step 1: Traverse the left subtree of the Root Node R in postorder
Step 2: Traverse the right subtree of the Root Node R in postorder
Step 3: Process the Root Node R
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Observations in Traversal Algorithms
• First node in the preorder traversal will be the Root Node
• Last node in the Postorder traversal will be the Root Node
• The Root Node will be present somewhere in between the first and
last node in the inorder traversal
• The inorder traversal of a binary search tree will list the elements in
the ascending order
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Problem Questions with Traversals
1. If preorder and inorder traversals of binary tree is given write its
postorder traversal
2. If postorder and inorder traversals of binary tree is given write its
preorder traversal
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
If preorder and inorder traversals of binary
tree is given write its postorder traversal
If preorder traversal of a binary tree is given as A, B, D, E, C, F, G and the inorder traversal is
given as D, B, E, A, F, C, G then write its postorder traversal.
From the preorder traversal we know that the first node ‘A’ is the root node and mark its
position in the inorder traversal.
D, B, E, A, F, C, G
All the nodes present to the left of the Root Node ‘A’ in the inorder traversal will be
present in the left subtree of the root node ‘A’ and all the nodes to the right of root node
will be present in the right subtree of the root node. Among the nodes to the left of root
node which is the immediate left child of root node ‘A’ is found accordingly: Among the
nodes D, B, E the node which appears first in the preorder traversal will be the immediate
left child of ‘A’. That is, node ‘B’ will be the immediate left child of node ‘A’. Keep
constructing the binary tree simultaneously.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
A
B
Mark the Node ‘B’ in the inorder traversal
D, B, E, A, F, C, G
There is one node to the left and right of node ‘B’ in the inorder traversal and
these nodes can be the immediate left and right child of node ‘B’. Hence left
child of node ‘B’ will be node ‘D’ and right child will be node ‘E’
Then the tree looks like as given below
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
Now we move towards the right side of node ‘A’ in the inorder traversal.
D, B, E, A, F, C, G
[Nodes which are represented in the binary tree are represented in red colour]
Among the nodes which lie towards the right side of node ‘A’ in the inorder
traversal the node which appears first in preorder traversal is node ‘C’. Hence
node ‘C’ will be added as immediate right child of node ‘A’
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
C
Mark the position of node ‘C’ in the inorder traversal.
D, B, E, A, F, C, G
There is one node to the left and one to the right of node ‘C’ in the inorder
traversal which happens to be the immediate left and right child of node ‘C’.
Hence we complete the tree as given below:
From the binary tree we can write the postorder traversal.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
C
F G
• If postorder and inorder traversals of binary tree is given write its preorder traversal
If postorder traversal of a binary tree is D, E, B, F, G, C, A and the inorder traversal is
D, B, E, A, F, C, G then write its preorder traversal.
In the postorder traversal we know that the last node ‘A’ is the Root Node.
Mark its position in the inorder traversal.
D, B, E, A, F, C, G
Among the nodes to the left of node ‘A’ in the inorder traversal the node which
appears last in postorder traversal is node ‘B’. Hence assign node ‘B’ as the immediate
left child of node ‘A’
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
Mark the node ‘B’ in the inorder traversal.
D, B, E, A, F, C, G
Since there is only one node to the left and right of node ‘B’ they will be
respectively the immediate left and right child of node ‘B’.
D, B, E, A, F, C, G
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
Among the nodes which appear to the right of node ‘A’ in the inorder traversal
the node which appears last in the post order traversal is node ‘C’ and it will be
added as immediate right child of node ‘A’
D, B, E, A, F, C, G
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
C
To the left and right of node ‘C’ there is one node each which will be added as
the left and right child of node ‘C’
From the binary tree we can write its preorder traversal.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A
B
D E
C
F G
Binary Search Tree
Binary Tree where every node has the following properties:
a) All the nodes in the left subtree are having value lesser than the node
b) All the nodes in the right subtree are having value greater than the node
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Insertion of a node in binary search
tree
A new node is always inserted at the leaf.
We start searching a node from the root
until we hit a leaf node.
Once a leaf node is found, the new node
is added as a child of the leaf node.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Example: Insertion of a new node in a Binary Search Tree
100 100
/  Insert 40 / 
20 500 ---------> 20 500
/  / 
10 30 10 30

40
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Binary Search Tree Program (Practical Program No. 15)
#include<stdio.h>
#include<stdlib.h>
struct n
{
struct node *left;
int info;
struct node *right;
};
typedef struct n node;
node *ROOT=NULL;
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
void main()
{
int option;
char choice = 'Y';
int item;
node *ptr;
clrscr();
while(choice == 'Y' || choice == 'y')
{
menu();
printf("nEnter your option number: ");
flushall();
scanf("%d",&option);
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
switch(option)
{
case 1: if(ROOT==NULL)
{
ptr = (node *)malloc(sizeof(node));
ROOT = ptr;
printf("nEnter the data item for the new node: ");
flushall();
scanf("%d",&ptr->info);
ptr->left = NULL;
ptr->right = NULL;
break;
}
printf("nEnter the data item for the new node: ");
flushall();
scanf("%d",&item);
insert(ROOT,ROOT,item,0);
break;
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
case 2: printf("nEnter the data item to be searched: ");
flushall();
scanf("%d",&item);
search(ROOT,item);
break;
case 3: inorder(ROOT);
break;
case 4: preorder(ROOT);
break;
case 5: postorder(ROOT);
break;
default: printf("nInvalid option No.");
break;
}
printf("nDo you wish to continue (y/n)");
flushall();
scanf("%c",&choice);
}/* end of while loop */
}//End of main function body
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
menu()
{
printf("n1.Creation of Binary search tree");
printf("n2.Search for a node");
printf("n3.Inorder Traversal");
printf("n4.Preorder Traversal");
printf("n5.Postorder Traversal");
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
insert(node *parent,node *p,int item,int flag)
{
if(p==NULL)
{
p = (node *)malloc(sizeof(node));
if(flag == 1)
{
parent->left = p;
}
else
{
parent->right = p;
}
p->left = NULL;
p-> right = NULL;
p->info = item;
return;
}
else
{
if(item==p->info)
{
printf("nItem found in the binary search tree");
return;
}
else
{
parent = p;
if(item < p->info)
{
printf("nDirected to the left link ");
flag = 1;
insert(parent,p->left,item,flag);
}
else
{
printf("nDirected to the right link ");
flag=2;
insert(parent,p->right,item,flag);
}
}
}
return;
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
inorder(node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("t%d",p->info);
inorder(p->right);
}
else
{
return;
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
ROOT
1000
1000
2000 5 3000
2000 3000
4000 3 5000 NULL 6 NULL
4000 5000
NULL 2 NULL NULL 4 NULL
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
in(NULL)
in(4000) Print 2
in(2000) Print 3 in(NULL)
in(1000) Print 5 in(5000)
in(3000) in(NULL)
Print 4
in(NULL) in(NULL)
Print 6
in(NULL)
inorder(node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("t%d",p->info);
inorder(p->right);
}
else
{
return;
}
}
preorder(node *p)
{
if(p!=NULL)
{
printf("n%d",p->info);
preorder(p->left);
preorder(p->right);
}
else
{
return;
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
postorder(node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("n%d",p->info);
}
else
{
return;
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
search(node *p,int item)
{
if(p!=NULL)
{
search(p->left,item);
if(item == p->info)
{
printf("nItem %d found at %u",item,p);
return;
}
search(p->right,item);
}
else
{
return;
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Complete Binary Tree
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
A complete binary tree is a binary tree in which all the
levels are completely filled except possibly the lowest one,
which is filled from the left.
Heap (Maxheap)
A complete binary tree where every node has value greater than its
children is defined as Heap or Maxheap.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Minheap
A complete binary tree where every node has value lesser than its
children is defined as minheap.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Inserting a node into a Heap
Suppose H is a heap with N elements, and suppose an ITEM of information
is given. We insert ITEM into the heap H as follows:
Step 1: First adjoin ITEM at the end of H so that it is still a complete binary
tree but not necessarily a heap.
Step 2: Then let ITEM rise to its appropriate place in H so that H is finally a
heap.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Example: Inserting a new node in a minheap
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Deleting the Root node of a Heap
Suppose H is a hep with N elements, and suppose we want to delete
the root node R of H. This is accomplished as follows:
Step 1: Assign the root R to some variable ITEM.
Step 2: Replace the deleted node R by the last node L of H so that H is
still a complete binary tree but not necessarily a heap
Step 3: Reheap Procedure – Let L sink to its appropriate place in H so
that H is finally a heap
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Example: Deleting the Root node of minheap
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Here the root node to be deleted gets replaced by the last node in the minheap so that the tree is still a complete binary
tree but not necessarily a heap
Still we observe that 48 is not in its correct position as 48 is having value greater than its new children 5 and 8. Hence we repeat
the process by swapping 48 with the smaller child 5.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Since 48 is larger than its children, it needs to trickle down into the correct position(Reheap procedure to be done). A comparison is
made or the two children of 48 and the smallest child 4 is chosen. Now 48 is swapped with this smaller child 4.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Still 48 is not in its correct position as it is greater than its new children 11 and 6. Hence we repeat the process of sinking 48 by
swapping it with the smallest child 6. After doing this swapping we get 48 placed in its correct position and the tree is a minheap.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Note:
If we are deleting the root node of a maxheap then the Reheap(sinking
procedure) happens by swapping the node with the largest among the
two children.
For getting the elements sorted in ascending order you can use
minheap and for getting elements sorted in descending order you can
use the maxheap during the heapsort technique.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Heap Sort Algorithm
Heapsort(A, N)
[A is an array with N elements. This algorithm sorts the elements of A using
heapsort technique.]
[Build a Heap]
Step 1: Repeatedly execute the steps 1a and 1b for the N elements and create a
heap
Step 1a: First adjoin ITEM at the end of H so that it is still a complete binary tree
but not necessarily a heap.
Step 1b: Then let ITEM rise to its appropriate place in H so that H is finally a heap.
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Step 2: Repeatedly print and delete the root of heap by executing the steps 20, 2b
and 2c until the heap becomes empty
Step 2a: Assign the root R to some variable ITEM.
Step 2b: Replace the deleted node R by the last node L of Heap H so that H is still
a complete binary tree but not necessarily a heap
Step 2c: Reheap Procedure – Let L sink to its appropriate place in H so that H is
finally a heap
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Heap Sort Program – Array Implementation
#include<stdio.h>
void main()
{
static int i,j,flag,temp,a[25],n,num;
clrscr();
printf("nEnter the no. of elements: ");
flushall();
scanf("%d",&n);
printf("nEnter the %d elements",n);
/*insert the first element as the root */
flushall();
scanf("%d",&a[1]);
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
/*insert the subsequent n-1 elements one at a time and creating a min heap simultaneously */
for(i=2;i<=n;i++)
{
flushall();
scanf("%d",&a[i]);
for(j=i;j>=2;j/=2)
{
if(a[j/2]>a[j])
{
temp = a[j/2];
a[j/2] = a[j];
a[j] = temp;
}
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
printf("nElements inserted as min heapn");
for(i=1;i<=n;i++)
{
printf("%dt",a[i]);
}
printf("n");
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
for(num=n;num>=1;)
{
/* last element in the heap is copied as the
first element(root) so that it is still a complete binary tree */
printf("%dt",a[1]);
a[1] = a[num];
num= num - 1;
/* let the new root sink to its appropriate position to
make it a min heap */
for(j=1;((j*2) <= num)||((j*2+1) <= num);)
{
if(j*2+1 > num)
{
if(a[j]<a[j*2])
{
break;
}
}
if( (a[j]<a[j*2]) && (a[j]<a[j*2+1]) )
{
break;
}
else
{
if( (a[j] > a[j*2]) && (a[j] > a[j*2+1]))
{
temp = a[j];
if(a[j*2] < a[j*2+1])
{
a[j] = a[j*2];
a[j*2] = temp;
j = j * 2;
}
else
{
a[j] = a[j*2+1];
a[j*2+1] = temp;
j=j*2+1;
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru
else
{
if(a[j] > a[j*2])
{
temp = a[j];
a[j] = a[j*2];
a[j*2] = temp;
j = j*2;
}
else
{
temp = a[j];
a[j] = a[j*2+1];
a[j*2+1] = temp;
j = j*2+1;
}
}
}
}
}
}
Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti
College(Autonomous) Bengaluru

More Related Content

Similar to Tree.pptx (20)

Data structure using c module 2
Data structure using c module 2Data structure using c module 2
Data structure using c module 2
 
DATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptxDATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptx
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structures
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Tree
TreeTree
Tree
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Introduction to Tree .pptx
Introduction to Tree .pptxIntroduction to Tree .pptx
Introduction to Tree .pptx
 
phylogenetics.pdf
phylogenetics.pdfphylogenetics.pdf
phylogenetics.pdf
 
Unit – vi tree
Unit – vi   treeUnit – vi   tree
Unit – vi tree
 
Binary trees
Binary treesBinary trees
Binary trees
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
Tree
TreeTree
Tree
 

More from JeoJoyA

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptxJeoJoyA
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxJeoJoyA
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxJeoJoyA
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxJeoJoyA
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxJeoJoyA
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxJeoJoyA
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary searchJeoJoyA
 
Linked list
Linked listLinked list
Linked listJeoJoyA
 

More from JeoJoyA (10)

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptx
 
OpenGL
OpenGLOpenGL
OpenGL
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptx
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptx
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptx
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptx
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
 
Linked list
Linked listLinked list
Linked list
 
Tree
TreeTree
Tree
 

Recently uploaded

FS P2 COMBO MSTA LAST PUSH past exam papers.
FS P2 COMBO MSTA LAST PUSH past exam papers.FS P2 COMBO MSTA LAST PUSH past exam papers.
FS P2 COMBO MSTA LAST PUSH past exam papers.takadzanijustinmaime
 
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...Scintica Instrumentation
 
Concept of gene and Complementation test.pdf
Concept of gene and Complementation test.pdfConcept of gene and Complementation test.pdf
Concept of gene and Complementation test.pdfCherry
 
Dr. E. Muralinath_ Blood indices_clinical aspects
Dr. E. Muralinath_ Blood indices_clinical  aspectsDr. E. Muralinath_ Blood indices_clinical  aspects
Dr. E. Muralinath_ Blood indices_clinical aspectsmuralinath2
 
Human genetics..........................pptx
Human genetics..........................pptxHuman genetics..........................pptx
Human genetics..........................pptxCherry
 
Cyanide resistant respiration pathway.pptx
Cyanide resistant respiration pathway.pptxCyanide resistant respiration pathway.pptx
Cyanide resistant respiration pathway.pptxCherry
 
Cyathodium bryophyte: morphology, anatomy, reproduction etc.
Cyathodium bryophyte: morphology, anatomy, reproduction etc.Cyathodium bryophyte: morphology, anatomy, reproduction etc.
Cyathodium bryophyte: morphology, anatomy, reproduction etc.Cherry
 
Understanding Partial Differential Equations: Types and Solution Methods
Understanding Partial Differential Equations: Types and Solution MethodsUnderstanding Partial Differential Equations: Types and Solution Methods
Understanding Partial Differential Equations: Types and Solution Methodsimroshankoirala
 
Plasmid: types, structure and functions.
Plasmid: types, structure and functions.Plasmid: types, structure and functions.
Plasmid: types, structure and functions.Cherry
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professormuralinath2
 
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry Areesha Ahmad
 
Energy is the beat of life irrespective of the domains. ATP- the energy curre...
Energy is the beat of life irrespective of the domains. ATP- the energy curre...Energy is the beat of life irrespective of the domains. ATP- the energy curre...
Energy is the beat of life irrespective of the domains. ATP- the energy curre...Nistarini College, Purulia (W.B) India
 
Taphonomy and Quality of the Fossil Record
Taphonomy and Quality of the  Fossil RecordTaphonomy and Quality of the  Fossil Record
Taphonomy and Quality of the Fossil RecordSangram Sahoo
 
X-rays from a Central “Exhaust Vent” of the Galactic Center Chimney
X-rays from a Central “Exhaust Vent” of the Galactic Center ChimneyX-rays from a Central “Exhaust Vent” of the Galactic Center Chimney
X-rays from a Central “Exhaust Vent” of the Galactic Center ChimneySérgio Sacani
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryAlex Henderson
 
Selaginella: features, morphology ,anatomy and reproduction.
Selaginella: features, morphology ,anatomy and reproduction.Selaginella: features, morphology ,anatomy and reproduction.
Selaginella: features, morphology ,anatomy and reproduction.Cherry
 
Site specific recombination and transposition.........pdf
Site specific recombination and transposition.........pdfSite specific recombination and transposition.........pdf
Site specific recombination and transposition.........pdfCherry
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learninglevieagacer
 
GBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisGBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisAreesha Ahmad
 

Recently uploaded (20)

FS P2 COMBO MSTA LAST PUSH past exam papers.
FS P2 COMBO MSTA LAST PUSH past exam papers.FS P2 COMBO MSTA LAST PUSH past exam papers.
FS P2 COMBO MSTA LAST PUSH past exam papers.
 
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
 
Concept of gene and Complementation test.pdf
Concept of gene and Complementation test.pdfConcept of gene and Complementation test.pdf
Concept of gene and Complementation test.pdf
 
Dr. E. Muralinath_ Blood indices_clinical aspects
Dr. E. Muralinath_ Blood indices_clinical  aspectsDr. E. Muralinath_ Blood indices_clinical  aspects
Dr. E. Muralinath_ Blood indices_clinical aspects
 
Human genetics..........................pptx
Human genetics..........................pptxHuman genetics..........................pptx
Human genetics..........................pptx
 
Cyanide resistant respiration pathway.pptx
Cyanide resistant respiration pathway.pptxCyanide resistant respiration pathway.pptx
Cyanide resistant respiration pathway.pptx
 
Cyathodium bryophyte: morphology, anatomy, reproduction etc.
Cyathodium bryophyte: morphology, anatomy, reproduction etc.Cyathodium bryophyte: morphology, anatomy, reproduction etc.
Cyathodium bryophyte: morphology, anatomy, reproduction etc.
 
Understanding Partial Differential Equations: Types and Solution Methods
Understanding Partial Differential Equations: Types and Solution MethodsUnderstanding Partial Differential Equations: Types and Solution Methods
Understanding Partial Differential Equations: Types and Solution Methods
 
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY // USES OF ANTIOBIOTICS TYPES OF ANTIB...
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY  // USES OF ANTIOBIOTICS TYPES OF ANTIB...ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY  // USES OF ANTIOBIOTICS TYPES OF ANTIB...
ABHISHEK ANTIBIOTICS PPT MICROBIOLOGY // USES OF ANTIOBIOTICS TYPES OF ANTIB...
 
Plasmid: types, structure and functions.
Plasmid: types, structure and functions.Plasmid: types, structure and functions.
Plasmid: types, structure and functions.
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
 
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
 
Energy is the beat of life irrespective of the domains. ATP- the energy curre...
Energy is the beat of life irrespective of the domains. ATP- the energy curre...Energy is the beat of life irrespective of the domains. ATP- the energy curre...
Energy is the beat of life irrespective of the domains. ATP- the energy curre...
 
Taphonomy and Quality of the Fossil Record
Taphonomy and Quality of the  Fossil RecordTaphonomy and Quality of the  Fossil Record
Taphonomy and Quality of the Fossil Record
 
X-rays from a Central “Exhaust Vent” of the Galactic Center Chimney
X-rays from a Central “Exhaust Vent” of the Galactic Center ChimneyX-rays from a Central “Exhaust Vent” of the Galactic Center Chimney
X-rays from a Central “Exhaust Vent” of the Galactic Center Chimney
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
 
Selaginella: features, morphology ,anatomy and reproduction.
Selaginella: features, morphology ,anatomy and reproduction.Selaginella: features, morphology ,anatomy and reproduction.
Selaginella: features, morphology ,anatomy and reproduction.
 
Site specific recombination and transposition.........pdf
Site specific recombination and transposition.........pdfSite specific recombination and transposition.........pdf
Site specific recombination and transposition.........pdf
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learning
 
GBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of AsepsisGBSN - Microbiology (Unit 4) Concept of Asepsis
GBSN - Microbiology (Unit 4) Concept of Asepsis
 

Tree.pptx

  • 1. Unit V: Tree Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 2. Tree Data Structure - Definition Tree is an example for a non linear data structure where nodes(elements) exhibit hierarchical relationship among them. As it is non linear in nature nodes can exist at random memory locations. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 3. Tree - Terminologies Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 4. Root Node Root node is the node which exist at the top of the Tree in Level zero. Every Tree data structure should have one and only one Root Node. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 5. Edge The connecting link between any two nodes(elements) of the tree is defined as an Edge. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 6. Parent Node The node which has a branch from it to any other node is called as a parent node. In other words, a node which has one or more children is defined as a parent node. In a general Tree data structure a parent can have any number of children. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, •Node A is the parent of nodes B and C •Node B is the parent of nodes D, E and F •Node C is the parent of nodes G and H •Node E is the parent of nodes I and J •Node G is the parent of node K
  • 7. Child Node A node which is a descendant of some node is defined as a child node. All nodes except the Root node are child nodes. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, •Nodes B and C are the children of node A •Nodes D, E and F are the children of node B •Nodes G and H are the children of node C •Nodes I and J are the children of node E •Node K is the child of node G
  • 8. Siblings Child nodes of the same parent are called siblings Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, •Nodes B and C are siblings •Nodes D, E and F are siblings •Nodes G and H are siblings •Nodes I and J are siblings
  • 9. Degree of a Node Degree of a node is the total number of children of the node. Degree of a Tree is the highest degree of the node among all the nodes of the Tree. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, •Degree of node A = 2 •Degree of node B = 3 •Degree of node C = 2 •Degree of node D = 0 •Degree of node E = 2 •Degree of node F = 0 •Degree of node G = 1 •Degree of node H = 0 •Degree of node I = 0 •Degree of node J = 0 •Degree of node K = 0
  • 10. Internal(Non-Terminal / Non-Leaf) Node The node which has at least one child is defined as Internal or Non Terminal or Non Leaf node. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, nodes A, B, C, E and G are internal nodes.
  • 11. Leaf Node (Terminal Node or External Node) A node which does not have any child is defined as a Leaf Node. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here, nodes D, I, J, F, K and H are leaf nodes.
  • 12. Level In a Tree each step from top to bottom is defined as a level of the Tree. Root Node is existing at Level Zero and level number increases by unity as we go down the Tree. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 13. Height or Depth of a Tree Height or Depth of a Tree is the maximum number of nodes in the longest branch of the Tree. It is usually one more than the largest level number. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 14. Subtree In a tree, each child from a node forms a subtree recursively. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 15. Forest A forest is a set of disjoint trees. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 16. Binary Trees A tree where every node can have maximum two children(zero child, one child or two children) is defined as binary tree. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru parent left child right child
  • 17. Maximum No. of nodes possible in a level of binary tree Maximum number of nodes possible in a level of binary tree is 2Level No. In Level Zero Maximum No. of nodes possible is 1 (Only Root Node available in Level Zero) In Level One Maximum No. of nodes possible is 2 In Level Two Maximum No. of nodes possible is 4 Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 18. Memory Representation of Binary Tree Binary Tree can be represented in the memory in two ways: 1. Array Representation 2. Linked Representation Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 19. Array Representation of Binary Tree In the array representation of binary tree the array indices are assumed to begin from 1st index and the root node is stored in the 1st index of the array. If L denote the index where a node is stored in the array then its left child will be stored in (2 * L)th index of the array and its right child will be stored in (2 * L + 1)th index of the array. If a left or right child does not exist for a node then the corresponding index location in the array is left blank. If L denote the index in the array where a node is stored then its parent will be stored in ( L / 2 )th index of the array. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 20. Binary Tree Array Representation with Index of Array Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 21. Linked Representation of Binary Tree In linked and dynamic representation each node constitutes of a data part and two link parts. The two link parts store address of left and right child nodes. Data part is used to store the information. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 22. Definition of a node in linked representation of Binary Tree struct n { struct n *left; int info; struct n *right; }; typedef struct n node; node *ROOT = NULL; Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 23. Traversal of Nodes in Binary Tree Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot randomly access a node in a tree. There are three ways which we use to traverse a tree − • Inorder Traversal • Preorder Traversal • Postorder Traversal Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 24. Inorder Traversal Algorithm Step 1: Traverse the left subtree of the Root Node R in inorder Step 2: Process the Root node R Step 3: Traverse the right subtree of the Root Node R in inorder Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 25. Preorder Traversal Algorithm Step 1: Process the Root node R Step 2: Traverse the left subtree of the Root Node R in preorder Step 3: Traverse the right subtree of the Root Node R in preorder Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 26. Postorder Traversl Algorithm Step 1: Traverse the left subtree of the Root Node R in postorder Step 2: Traverse the right subtree of the Root Node R in postorder Step 3: Process the Root Node R Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 27. Observations in Traversal Algorithms • First node in the preorder traversal will be the Root Node • Last node in the Postorder traversal will be the Root Node • The Root Node will be present somewhere in between the first and last node in the inorder traversal • The inorder traversal of a binary search tree will list the elements in the ascending order Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 28. Problem Questions with Traversals 1. If preorder and inorder traversals of binary tree is given write its postorder traversal 2. If postorder and inorder traversals of binary tree is given write its preorder traversal Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 29. If preorder and inorder traversals of binary tree is given write its postorder traversal If preorder traversal of a binary tree is given as A, B, D, E, C, F, G and the inorder traversal is given as D, B, E, A, F, C, G then write its postorder traversal. From the preorder traversal we know that the first node ‘A’ is the root node and mark its position in the inorder traversal. D, B, E, A, F, C, G All the nodes present to the left of the Root Node ‘A’ in the inorder traversal will be present in the left subtree of the root node ‘A’ and all the nodes to the right of root node will be present in the right subtree of the root node. Among the nodes to the left of root node which is the immediate left child of root node ‘A’ is found accordingly: Among the nodes D, B, E the node which appears first in the preorder traversal will be the immediate left child of ‘A’. That is, node ‘B’ will be the immediate left child of node ‘A’. Keep constructing the binary tree simultaneously. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A A B
  • 30. Mark the Node ‘B’ in the inorder traversal D, B, E, A, F, C, G There is one node to the left and right of node ‘B’ in the inorder traversal and these nodes can be the immediate left and right child of node ‘B’. Hence left child of node ‘B’ will be node ‘D’ and right child will be node ‘E’ Then the tree looks like as given below Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E
  • 31. Now we move towards the right side of node ‘A’ in the inorder traversal. D, B, E, A, F, C, G [Nodes which are represented in the binary tree are represented in red colour] Among the nodes which lie towards the right side of node ‘A’ in the inorder traversal the node which appears first in preorder traversal is node ‘C’. Hence node ‘C’ will be added as immediate right child of node ‘A’ Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E C
  • 32. Mark the position of node ‘C’ in the inorder traversal. D, B, E, A, F, C, G There is one node to the left and one to the right of node ‘C’ in the inorder traversal which happens to be the immediate left and right child of node ‘C’. Hence we complete the tree as given below: From the binary tree we can write the postorder traversal. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E C F G
  • 33. • If postorder and inorder traversals of binary tree is given write its preorder traversal If postorder traversal of a binary tree is D, E, B, F, G, C, A and the inorder traversal is D, B, E, A, F, C, G then write its preorder traversal. In the postorder traversal we know that the last node ‘A’ is the Root Node. Mark its position in the inorder traversal. D, B, E, A, F, C, G Among the nodes to the left of node ‘A’ in the inorder traversal the node which appears last in postorder traversal is node ‘B’. Hence assign node ‘B’ as the immediate left child of node ‘A’ Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B
  • 34. Mark the node ‘B’ in the inorder traversal. D, B, E, A, F, C, G Since there is only one node to the left and right of node ‘B’ they will be respectively the immediate left and right child of node ‘B’. D, B, E, A, F, C, G Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E
  • 35. Among the nodes which appear to the right of node ‘A’ in the inorder traversal the node which appears last in the post order traversal is node ‘C’ and it will be added as immediate right child of node ‘A’ D, B, E, A, F, C, G Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E C
  • 36. To the left and right of node ‘C’ there is one node each which will be added as the left and right child of node ‘C’ From the binary tree we can write its preorder traversal. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A B D E C F G
  • 37. Binary Search Tree Binary Tree where every node has the following properties: a) All the nodes in the left subtree are having value lesser than the node b) All the nodes in the right subtree are having value greater than the node Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 38. Insertion of a node in binary search tree A new node is always inserted at the leaf. We start searching a node from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 39. Example: Insertion of a new node in a Binary Search Tree 100 100 / Insert 40 / 20 500 ---------> 20 500 / / 10 30 10 30 40 Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 40. Binary Search Tree Program (Practical Program No. 15) #include<stdio.h> #include<stdlib.h> struct n { struct node *left; int info; struct node *right; }; typedef struct n node; node *ROOT=NULL; Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 41. void main() { int option; char choice = 'Y'; int item; node *ptr; clrscr(); while(choice == 'Y' || choice == 'y') { menu(); printf("nEnter your option number: "); flushall(); scanf("%d",&option); Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 42. switch(option) { case 1: if(ROOT==NULL) { ptr = (node *)malloc(sizeof(node)); ROOT = ptr; printf("nEnter the data item for the new node: "); flushall(); scanf("%d",&ptr->info); ptr->left = NULL; ptr->right = NULL; break; } printf("nEnter the data item for the new node: "); flushall(); scanf("%d",&item); insert(ROOT,ROOT,item,0); break; Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 43. case 2: printf("nEnter the data item to be searched: "); flushall(); scanf("%d",&item); search(ROOT,item); break; case 3: inorder(ROOT); break; case 4: preorder(ROOT); break; case 5: postorder(ROOT); break; default: printf("nInvalid option No."); break; } printf("nDo you wish to continue (y/n)"); flushall(); scanf("%c",&choice); }/* end of while loop */ }//End of main function body Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 44. menu() { printf("n1.Creation of Binary search tree"); printf("n2.Search for a node"); printf("n3.Inorder Traversal"); printf("n4.Preorder Traversal"); printf("n5.Postorder Traversal"); } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 45. insert(node *parent,node *p,int item,int flag) { if(p==NULL) { p = (node *)malloc(sizeof(node)); if(flag == 1) { parent->left = p; } else { parent->right = p; } p->left = NULL; p-> right = NULL; p->info = item; return; } else { if(item==p->info) { printf("nItem found in the binary search tree"); return; } else { parent = p; if(item < p->info) { printf("nDirected to the left link "); flag = 1; insert(parent,p->left,item,flag); } else { printf("nDirected to the right link "); flag=2; insert(parent,p->right,item,flag); } } } return; } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 46. inorder(node *p) { if(p!=NULL) { inorder(p->left); printf("t%d",p->info); inorder(p->right); } else { return; } } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 47. ROOT 1000 1000 2000 5 3000 2000 3000 4000 3 5000 NULL 6 NULL 4000 5000 NULL 2 NULL NULL 4 NULL Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru in(NULL) in(4000) Print 2 in(2000) Print 3 in(NULL) in(1000) Print 5 in(5000) in(3000) in(NULL) Print 4 in(NULL) in(NULL) Print 6 in(NULL) inorder(node *p) { if(p!=NULL) { inorder(p->left); printf("t%d",p->info); inorder(p->right); } else { return; } }
  • 50. search(node *p,int item) { if(p!=NULL) { search(p->left,item); if(item == p->info) { printf("nItem %d found at %u",item,p); return; } search(p->right,item); } else { return; } } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 51. Complete Binary Tree Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru A complete binary tree is a binary tree in which all the levels are completely filled except possibly the lowest one, which is filled from the left.
  • 52. Heap (Maxheap) A complete binary tree where every node has value greater than its children is defined as Heap or Maxheap. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 53. Minheap A complete binary tree where every node has value lesser than its children is defined as minheap. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 54. Inserting a node into a Heap Suppose H is a heap with N elements, and suppose an ITEM of information is given. We insert ITEM into the heap H as follows: Step 1: First adjoin ITEM at the end of H so that it is still a complete binary tree but not necessarily a heap. Step 2: Then let ITEM rise to its appropriate place in H so that H is finally a heap. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 55. Example: Inserting a new node in a minheap Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 56. Deleting the Root node of a Heap Suppose H is a hep with N elements, and suppose we want to delete the root node R of H. This is accomplished as follows: Step 1: Assign the root R to some variable ITEM. Step 2: Replace the deleted node R by the last node L of H so that H is still a complete binary tree but not necessarily a heap Step 3: Reheap Procedure – Let L sink to its appropriate place in H so that H is finally a heap Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 57. Example: Deleting the Root node of minheap Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 58. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru Here the root node to be deleted gets replaced by the last node in the minheap so that the tree is still a complete binary tree but not necessarily a heap
  • 59. Still we observe that 48 is not in its correct position as 48 is having value greater than its new children 5 and 8. Hence we repeat the process by swapping 48 with the smaller child 5. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 60. Since 48 is larger than its children, it needs to trickle down into the correct position(Reheap procedure to be done). A comparison is made or the two children of 48 and the smallest child 4 is chosen. Now 48 is swapped with this smaller child 4. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 61. Still 48 is not in its correct position as it is greater than its new children 11 and 6. Hence we repeat the process of sinking 48 by swapping it with the smallest child 6. After doing this swapping we get 48 placed in its correct position and the tree is a minheap. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 62. Note: If we are deleting the root node of a maxheap then the Reheap(sinking procedure) happens by swapping the node with the largest among the two children. For getting the elements sorted in ascending order you can use minheap and for getting elements sorted in descending order you can use the maxheap during the heapsort technique. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 63. Heap Sort Algorithm Heapsort(A, N) [A is an array with N elements. This algorithm sorts the elements of A using heapsort technique.] [Build a Heap] Step 1: Repeatedly execute the steps 1a and 1b for the N elements and create a heap Step 1a: First adjoin ITEM at the end of H so that it is still a complete binary tree but not necessarily a heap. Step 1b: Then let ITEM rise to its appropriate place in H so that H is finally a heap. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 64. Step 2: Repeatedly print and delete the root of heap by executing the steps 20, 2b and 2c until the heap becomes empty Step 2a: Assign the root R to some variable ITEM. Step 2b: Replace the deleted node R by the last node L of Heap H so that H is still a complete binary tree but not necessarily a heap Step 2c: Reheap Procedure – Let L sink to its appropriate place in H so that H is finally a heap Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 65. Heap Sort Program – Array Implementation #include<stdio.h> void main() { static int i,j,flag,temp,a[25],n,num; clrscr(); printf("nEnter the no. of elements: "); flushall(); scanf("%d",&n); printf("nEnter the %d elements",n); /*insert the first element as the root */ flushall(); scanf("%d",&a[1]); Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 66. /*insert the subsequent n-1 elements one at a time and creating a min heap simultaneously */ for(i=2;i<=n;i++) { flushall(); scanf("%d",&a[i]); for(j=i;j>=2;j/=2) { if(a[j/2]>a[j]) { temp = a[j/2]; a[j/2] = a[j]; a[j] = temp; } } } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 67. printf("nElements inserted as min heapn"); for(i=1;i<=n;i++) { printf("%dt",a[i]); } printf("n"); Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 68. Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru for(num=n;num>=1;) { /* last element in the heap is copied as the first element(root) so that it is still a complete binary tree */ printf("%dt",a[1]); a[1] = a[num]; num= num - 1; /* let the new root sink to its appropriate position to make it a min heap */ for(j=1;((j*2) <= num)||((j*2+1) <= num);) { if(j*2+1 > num) { if(a[j]<a[j*2]) { break; } } if( (a[j]<a[j*2]) && (a[j]<a[j*2+1]) ) { break; }
  • 69. else { if( (a[j] > a[j*2]) && (a[j] > a[j*2+1])) { temp = a[j]; if(a[j*2] < a[j*2+1]) { a[j] = a[j*2]; a[j*2] = temp; j = j * 2; } else { a[j] = a[j*2+1]; a[j*2+1] = temp; j=j*2+1; } } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru
  • 70. else { if(a[j] > a[j*2]) { temp = a[j]; a[j] = a[j*2]; a[j*2] = temp; j = j*2; } else { temp = a[j]; a[j] = a[j*2+1]; a[j*2+1] = temp; j = j*2+1; } } } } } } Prof. Jeo Joy A, Dept. of Computer Science, Kristu Jayanti College(Autonomous) Bengaluru