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
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;
}