DS - UNIT - 4 (Trees)
DS - UNIT - 4 (Trees)
Syllabus:
Trees: Representation of Trees, Binary Trees Abstract Data Type, Properties of
BinaryTrees, Binary Tree Representations, Binary Tree Traversals,Heap Abstract Data
Type, Insertion into a max heap, Deletion from a max heap, Heap Sort. Introduction to
Binary Search Trees, Searching a Binary Search Tree, Inserting an Element into a
Binary Search Tree, Deleting an Element from a Binary Search Tree,Height of a Binary
Search Tree.
Tree - Terminology
In linear data structure data is organized in sequential order and in non-linear data
structure data is organized in random order. A tree is a very popular non-linear data
structure used in a wide range of applications. A tree data structure can be defined as
follows...
Tree is a non-linear data structure which organizes data in hierarchical structure and
this is a recursive definition.
A tree data structure can also be defined as follows...
Tree data structure is a collection of data (Node) which is organized in hierarchical
structure recursively
In tree data structure, every individual element is called as Node. Node in a tree data
structure stores the actual data of that particular element and link to next element in
hierarchical structure.
In a tree data structure, if we have N number of nodes then we can have a maximum of
N-1 number of links.
Example
Terminology
In a tree data structure, we use the following terminology...
1. Root
In a tree data structure, the first node is called as Root Node. Every tree must have a
root node. We can say that the root node is the origin of the tree data structure. In any
tree, there must be only one root node. We never have multiple root nodes in a tree.
2. Edge
In a tree data structure, the connecting link between any two nodes is called as EDGE.
In a tree with 'N' number of nodes there will be a maximum of 'N-1' number of edges.
3. Parent
In a tree data structure, the node which is a predecessor of any node is called as
PARENT NODE. In simple words, the node which has a branch from it to any other
node is called a parent node. Parent node can also be defined as "The node which
has child / children".
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD
Node. In simple words, the node which has a link from its parent node is called as child
node. In a tree, any parent node can have any number of child nodes. In a tree, all the
nodes except root are child nodes.
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simple words, the nodes with the same parent are called Sibling nodes.
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node.
In simple words, a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes. External
node is also a node with no child. In a tree, leaf node is also called as 'Terminal' node.
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL
Node. In simple words, an internal node is a node with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The
root node is also said to be Internal Node if the tree has more than one node.
Internal nodes are also called as 'Non-Terminal' nodes.
8. Degree
In a tree data structure, the total number of children of a node is called as DEGREE of
that Node. In simple words, the Degree of a node is total number of children it has. The
highest degree of a node among all the nodes in a tree is called as 'Degree of Tree'
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root
node are at Level 1 and the children of the nodes which are at Level 1 will be at Level 2
and so on... In simple words, in a tree each step from top to bottom is called as a Level
and the Level count starts with '0' and incremented by one at each level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a particular node in
the longest path is called as HEIGHT of that Node. In a tree, height of the root node is
said to be height of the tree. In a tree, height of all leaf nodes is '0'.
11. Depth
In a tree data structure, the total number of egdes from root node to a particular node is
called as DEPTH of that Node. In a tree, the total number of edges from root node to a
leaf node in the longest path is said to be Depth of the tree. In simple words, the
highest depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth
of the root node is '0'.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another
node is called as PATH between that two Nodes. Length of a Path is total number of
nodes in that path. In below example the path A - B - E - J has length 4.
13. Sub Tree
In a tree data structure, each child from a node forms a subtree recursively. Every child
node will form a subtree on its parent node.
Tree Representations
A tree data structure can be represented in two methods. Those methods are as
follows...
1. List Representation
2. Left Child - Right Sibling Representation
Consider the following tree...
1. List Representation
In this representation, we use two types of nodes one for representing the node with
data called 'data node' and another for representing only references called 'reference
node'. We start with a 'data node' from the root node in the tree. Then it is linked to an
internal node through a 'reference node' which is further linked to any other node
directly. This process repeats for all the nodes in the tree.
The above example tree can be represented using List representation as follows...
namely Data field, Left child reference field and Right sibling reference field. Data field
stores the actual value of a node, left reference field stores the address of the left child
and right reference field stores the address of the right sibling node. Graphical
node has left a child, then left reference field stores the address of that left child node
otherwise stores NULL. If that node has the right sibling, then right reference field stores
The above example tree can be represented using Left Child - Right Sibling
representation as follows...
Binary Tree Data Structure
In a normal tree, every node can have any number of children. A binary tree is a special
type of tree data structure in which every node can have a maximum of 2 children.
One is known as a left child and the other is known as right child.
A tree in which every node can have a maximum of two children is called Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children but not
more than 2 children.
Example
A binary tree in which every node has either two or zero number of children is called
Strictly Binary Tree
Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree
Strictly binary tree data structure is used to represent mathematical expressions.
Example
A binary tree in which every internal node has exactly two children and all leaf nodes
are at same level is called Complete Binary Tree.
The full binary tree obtained by adding dummy nodes to a binary tree is called as
Extended Binary Tree.
In above figure, a normal binary tree is converted into full binary tree by adding dummy
nodes (In pink colour).
Binary Tree Representations
A binary tree data structure is represented using two methods. Those methods are as
follows...
1. Array Representation
2. Linked List Representation
Consider the following binary tree...
To represent a binary tree of depth 'n' using array representation, we need one
consists of three fields. First field for storing left child address, second for storing actual
The above example of the binary tree represented using Linked list representation is
shown as follows...
Binary Tree Traversals
When we wanted to display a binary tree, we need to follow some order in which all the
nodes of that binary tree must be displayed. In any binary tree, displaying order of
Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal
Consider the following binary tree...
traversal, the left child node is visited first, then the root node is visited and later we go
for visiting the right child node. This in-order traversal is applicable for every root node
of all subtrees in the tree. This is performed recursively for all nodes in the tree.
In the above example of a binary tree, first we try to visit left child of root node 'A', but
A's left child 'B' is a root node for left subtree. so we try to visit its (B's) left child 'D' and
again D is a root for subtree with nodes D, I and J. So we try to visit its left child 'I' and it
is the leftmost child. So first we visit 'I' then go for its root node 'D' and later we visit D's
right child 'J'. With this we have completed the left part of node B. Then visit 'B' and
next B's right child 'F' is visited. With this we have completed left part of node A. Then
visit root node 'A'. With this we have completed left and root parts of node A. Then we
go for the right part of the node A. In right of A again there is a subtree with root C. So
go for left child of C and again it is a subtree with root G. But G does not have left part
so we visit 'G' and then visit G's right child K. With this we have completed the left part
of node C. Then visit root node 'C' and next visit C's right child 'H' which is the rightmost
In-Order Traversal.
I-D-J-B-F-A-G-K-C-H
In this traversal, the root node is visited first, then its left child and later its right child.
This pre-order traversal is applicable for every root node of all subtrees in the tree.
In the above example of binary tree, first we visit root node 'A' then visit its left child 'B'
which is a root for D and F. So we visit B's left child 'D' and again D is a root for I and J.
So we visit D's left child 'I' which is the leftmost child. So next we go for visiting D's right
child 'J'. With this we have completed root, left and right parts of node D and root, left
parts of node B. Next visit B's right child 'F'. With this we have completed root and left
parts of node A. So we go for A's right child 'C' which is a root node for G and H. After
visiting C, we go for its left child 'G' which is a root for node K. So next we visit left of G,
but it does not have left child so we go for G's right child 'K'. With this, we have
completed node C's root and left parts. Next visit C's right child 'H' which is the
That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order
Traversal.
struct Node{
int data;
struct Node *left;
struct Node *right;
};
void main(){
int choice, value;
clrscr();
printf("\n----- Binary Tree -----\n");
while(1){
printf("\n***** MENU *****\n");
printf("1. Insert\n2. Display\n3. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("\nEnter the value to be insert: ");
scanf("%d", &value);
root = insert(root,value);
break;
case 2: display(root); break;
case 3: exit(0);
default: printf("\nPlease select correct operations!!!\n");
}
}
}
tree with special characteristics. In a heap data structure, nodes are arranged based on
their values. A heap data structure some times also called as Binary Heap.
There are two types of heap data structures and they are as follows...
1. Max Heap
2. Min Heap
Every heap data structure has the following properties...
Property #2 (Structural): All levels in a heap must be full except the last level and all
nodes must be filled from left to right strictly.
Max Heap
Max heap data structure is a specialized full binary tree data structure. In a max heap
nodes are arranged based on node value.
Max heap is defined as follows...
Max heap is a specialized full binary tree in which every parent node contains greater or
equal value than its child nodes.
Example
Above tree is satisfying both Ordering property and Structural property according to the
Max Heap data structure.
Example
Consider the above max heap. Insert a new node with value 85.
Step 1 - Insert the newNode with value 85 as last leaf from left to right. That
means newNode is added as a right child of node with value 75. After adding
max heap is as follows...
Step 2 - Compare
newNode value (85) with its Parent node value (75). That means 85 > 75
Step 3 - Here
newNode value (85) is greater than its parent value (75), then swap both of
them. After swapping, max heap is as follows...
Deleting root node from a max heap is little difficult as it disturbs the max heap
properties. We use the following steps to delete the root node from a max heap...
Step 1 - Swap the root node with last node in max heap
Step 2 - Delete last node.
Step 3 - Now, compare root value with its left child value.
Step 4 - If root value is smaller than its left child, then compare left child with
its right sibling. Else goto Step 6
Step 5 - If left child value is larger than its right sibling, then swap root with
left child otherwise swap root with its right child.
Step 6 - If root value is larger than its left child, then compare root value with
its right child value.
Step 7 - If root value is smaller than its right child, then swap root with right
child otherwise stop the process.
Step 8 - Repeat the same until root node fixes at its exact position.
Example
Consider the above max heap. Delete root node (90) from the max heap.
Step 1 - Swap the root node (90) with last node 75 in max heap. After
swapping max heap is as follows...
Step 2 - Delete last node. Here the last node is 90. After deleting node with value
90 from heap, max heap is as follows...
Step 3 - Compare root node (75) with its left child (89).
Here, root value (75) is smaller than its left child value (89). So, compare left
child (89) with its right sibling (70).
Step 4 - Here, left child value (89) is larger than its right sibling (70), So,
swap root (75) with left child (89).
Step 5 - Now, again compare 75 with its left child (36).
Here, node with value 75 is larger than its left child. So, we compare node 75
with its right child 85.
Step 6 - Here, node with value 75 is smaller than its right child (85). So, we
swap both of them. After swapping max heap is as follows...
Step 7 - Now, compare node with value 75 with its left child (15).
Here, node with value 75 is larger than its left child (15) and it does not have right child.
So we stop the process.
Heapsort algorithm uses one of the tree concepts called Heap Tree. In this sorting
algorithm, we use Max Heap to arrange list of elements in Descending order and Min
Step by Step Process: The Heap sort algorithm to arrange a list of elements in
Example
// Implementation of Heap Sort in C
#include <stdio.h>
// Function to swap the position of two elements in an array
void swap(int *a, int *b) {
int tempvar = *a;
*a = *b;
*b = tempvar;
}
// Main function
void heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
To sort an unsorted list with 'n' number of elements, following are the complexities...
In this article, we will discuss the Binary search tree. This article will be very helpful and
informative to the students with technical background as it is an important topic of their
course.
Before moving directly to the binary search tree, let's first see a brief description of the
tree.
What is a tree?
A tree is a kind of data structure that is used to represent the data in hierarchical form. It
can be defined as a collection of objects or entities called as nodes that are linked
together to simulate a hierarchy. Tree is a non-linear data structure as the data in a tree
is not stored linearly or sequentially.
A binary search tree follows some order to arrange the elements. In a Binary search
tree, the value of left node must be smaller than the parent node, and the value of right
node must be greater than the parent node. This rule is applied recursively to the left
and right subtrees of the root.
In the above figure, we can observe that the root node is 40, and all the nodes of the left
subtree are smaller than the root node, and all the nodes of the right subtree are greater
than the root node.
Similarly, we can see the left child of root node is greater than its left child and smaller
than its right child. So, it also satisfies the property of binary search tree. Therefore, we
can say that the tree in the above image is a binary search tree.
Suppose if we change the value of node 35 to 55 in the above tree, check whether the
tree will be binary search tree or not.
In the above tree, the value of root node is 40, which is greater than its left child 30 but
smaller than right child of 30, i.e., 55. So, the above tree does not satisfy the property of
Binary search tree. Therefore, the above tree is not a binary search tree.
○ Searching an element in the Binary search tree is easy as we always have a hint
that which subtree has the desired element.
○ As compared to array and linked lists, insertion and deletion operations are faster
in BST.
Now, let's see the creation of binary search tree using an example.
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
○ First, we have to insert 45 into the tree as the root of the tree.
○ Then, read the next element; if it is smaller than the root node, insert it as the
root of the left subtree, and move to the next element.
○ Otherwise, if the element is larger than the root node, then insert it as the root of
the right subtree.
Now, let's see the process of creating the Binary search tree using the given data
element. The process of creating the BST is shown below -
As 15 is smaller than 45, so insert it as the root node of the left subtree.
As 79 is greater than 45, so insert it as the root node of the right subtree.
Step 4 - Insert 90.
90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.
55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.
Step 7 - Insert 12.
12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right
subtree of 10.
20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.
Now, the creation of binary search tree is completed. After that, let's move towards the
operations that can be performed on Binary search tree.
We can perform insert, delete and search operations on the binary search tree.
1. First, compare the element to be searched with the root element of the tree.
2. If root is matched with the target element, then return the node's location.
3. If it is not matched, then check whether the item is less than the root element, if it
is smaller than the root element, then move to the left subtree.
4. If it is larger than the root element, then move to the right subtree.
Now, let's understand the searching in binary tree using an example. We are taking the
binary search tree formed above. Suppose we have to find node 20 from the below tree.
Step1:
Step2:
Step3:
Now, let's see the algorithm to search an element in the Binary search tree.
Now let's understand how the deletion is performed on a binary search tree. We will
also see an example to delete an element from the given tree.
Deletion in Binary Search tree
In a binary search tree, we must delete a node from the tree by keeping in mind that the
property of BST is not violated. To delete a node from BST, there are three possible
situations occur -
It is the simplest case to delete a node in BST. Here, we have to replace the leaf node
with NULL and simply free the allocated space.
We can see the process to delete a leaf node from BST in the below image. In below
image, suppose we have to delete node 90, as the node to be deleted is a leaf node, so
it will be replaced with NULL, and the allocated space will free.
In this case, we have to replace the target node with its child, and then delete the child
node. It means that after replacing the target node with its child node, the child node will
now contain the value to be deleted. So, we simply have to replace the child node with
NULL and free up the allocated space.
We can see the process of deleting a node with one child from BST in the below image.
In the below image, suppose we have to delete the node 79, as the node to be deleted
has only one child, so it will be replaced with its child 55.
So, the replaced node 79 will now be a leaf node that can be easily deleted.
This case of deleting a node in BST is a bit complex among other two cases. In such a
case, the steps to be followed are listed as follows -
○ After that, replace that node with the inorder successor until the target node is
placed at the leaf of tree.
○ And at last, replace the node with NULL and free up the allocated space.
The inorder successor is required when the right child of the node is not empty. We can
obtain the inorder successor by finding the minimum element in the right child of the
node.
We can see the process of deleting a node with two children from BST in the below
image. In the below image, suppose we have to delete node 45 that is the root node, as
the node to be deleted has two children, so it will be replaced with its inorder successor.
Now, node 45 will be at the leaf of the tree so that it can be deleted easily.
Now let's understand how insertion is performed on a binary search tree.
A new key in BST is always inserted at the leaf. To insert an element in BST, we have to
start searching from the root node; if the node to be inserted is less than the root node,
then search for an empty location in the left subtree. Else, search for the empty location
in the right subtree and insert the data. Insert in BST is similar to searching, as we
always have to maintain the rule that the left subtree is smaller than the root, and right
subtree is larger than the root.
Now, let's see the process of inserting a node into BST using an example.
The complexity of the Binary Search tree
Let's see the time and space complexity of the Binary search tree. We will see the time
complexity for insertion, deletion, anTns in best case, average case, and worst case.
1. Time Complexity
Operation Best case time Average case time Worst case time
s complexity complexity complexity
Insertion O(n)
Deletion O(n)
Search O(n)