Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Unit 4

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...

2. Left Child - Right Sibling Representation


In this representation, we use a list with one type of node which consists of three fields

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

representation of that node is as follows...


In this representation, every node's data field stores the actual value of that node. If that

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 address of right sibling node otherwise stores NULL.

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

There are different types of binary trees and they are...

1. Strictly Binary Tree


In a binary tree, every node can have a maximum of two children. But in strictly binary
tree, every node should have exactly two children or none. That means every internal
node must have exactly two children. A strictly Binary Tree can be defined as follows...

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

2. Complete Binary Tree


In a binary tree, every node can have a maximum of two children. But in strictly binary
tree, every node should have exactly two children or none and in complete binary tree
all the nodes must have exactly two children and at every level of complete binary tree
there must be 2level number of nodes. For example at level 2 there must be 22 = 4
nodes and at level 3 there must be 23 = 8 nodes.

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.

Complete binary tree is also called as Perfect Binary Tree


3. Extended Binary Tree
A binary tree can be converted into Full Binary tree by adding dummy nodes to existing
nodes wherever required.

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...

1. Array Representation of Binary Tree


In array representation of a binary tree, we use one-dimensional array (1-D Array) to

represent a binary tree.

Consider the above example of a binary tree and it is represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one

dimensional array with a maximum size of 2n + 1.


2. Linked List Representation of Binary Tree
We use a double linked list to represent a binary tree. In a double linked list, every node

consists of three fields. First field for storing left child address, second for storing actual

data and third for storing right child address.

In this linked list representation, a node has the following structure...

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

nodes depends on the traversal method.

Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.

There are three types of binary tree traversals.

1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal
Consider the following binary tree...

1. In - Order Traversal ( leftChild - root - rightChild )


In In-Order traversal, the root node is visited between the left child and right child. In this

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

child in the tree. So we stop the process.

That means here we have visited in the order of I - D - J - B - F - A - G - K - C - H using

In-Order Traversal.

In-Order Traversal for above example of binary tree is

I-D-J-B-F-A-G-K-C-H

2. Pre - Order Traversal ( root - leftChild - rightChild )


In Pre-Order traversal, the root node is visited before the left child and right child nodes.

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

rightmost child in the tree. So we stop the process.

That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order
Traversal.

Pre-Order Traversal for above example binary tree is


A-B-D-I-J-F-C-G-K-H

3. Post - Order Traversal ( leftChild - rightChild - root )


In Post-Order traversal, the root node is visited after left child and right child. In this
traversal, left child node is visited first, then its right child and then its root node. This is
recursively performed until the right most node is visited.

Here we have visited in the order of I - J - D - F - B - K - G - H - C - A using Post-Order


Traversal.
Post-Order Traversal for above example binary tree is
I-J-D-F-B-K-G-H-C-A
Program to Create Binary Tree and display using In-Order Traversal - C
Programming
#include<stdio.h>
#include<conio.h>

struct Node{
int data;
struct Node *left;
struct Node *right;
};

struct Node *root = NULL;


int count = 0;

struct Node* insert(struct Node*, int);


void display(struct Node*);

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

struct Node* insert(struct Node *root,int value){


struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(root == NULL){
newNode->left = newNode->right = NULL;
root = newNode;
count++;
}
else{
if(count%2 != 0)
root->left = insert(root->left,value);
else
root->right = insert(root->right,value);
}
return root;
}
// display is performed by using Inorder Traversal
void display(struct Node *root)
{
if(root != NULL){
display(root->left);
printf("%d\t",root->data);
display(root->right);
}
}
Output
Properties of BinaryTrees

Some of the important properties of a binary tree as follows


Max Heap Datastructure
Heap data structure is a specialized binary tree-based data structure. Heap is a binary

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 #1 (Ordering): Nodes must be arranged in an order according to their values

based on Max heap or Min heap.

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.

Operations on Max Heap


The following operations are performed on a Max heap data structure...
1. Finding Maximum
2. Insertion
3. Deletion

Finding Maximum Value Operation in Max Heap


Finding the node which has maximum value in a max heap is very simple. In a max
heap, the root node has the maximum value than all other nodes. So, directly we can
display root node value as the maximum value in max heap.
Insertion Operation in Max Heap
Insertion Operation in max heap is performed as follows...
​ Step 1 - Insert the newNode as last leaf from left to right.
​ Step 2 - Compare newNode value with its Parent node.
​ Step 3 - If newNode value is greater than its parent, then swap both of them.
​ Step 4 - Repeat step 2 and step 3 until newNode value is less than its parent
node (or) newNode reaches to root.

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...

​ Step 4 - Now, again


compare newNode value (85) with its parent node value (89).
Here, newNode value (85) is smaller than its parent node value (89). So, we stop
insertion process. Finally, max heap after insertion of a new node with value 85 is as
follows...
Deletion Operation in Max Heap
In a max heap, deleting the last node is very simple as it does not disturb max heap
properties.

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.

Finally, max heap after deleting root node (90) is as follows...


Heap Sort Algorithm
Heap sort is one of the sorting algorithms used to arrange a list of elements in order.

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

Heap to arrange list elements in Ascending order.

Step by Step Process: The Heap sort algorithm to arrange a list of elements in

ascending order is performed using following steps…

Step 1 - Construct a Binary Tree with given list of Elements.

​ Step 2 - Transform the Binary Tree into Min Heap.


​ Step 3 - Delete the root element from Min Heap using Heapify method.
​ Step 4 - Put the deleted element into the Sorted list.
​ Step 5 - Repeat the same until Min Heap becomes empty.
​ Step 6 - Display the sorted list.

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

void heapify(int arr[], int n, int i) {


// Finding the greatest among root, leftSide child, and rightSide child of the tree
int greatest = i;
int leftSide = 2 * i + 1;
int rightSide = 2 * i + 2;

if (leftSide < n && arr[leftSide] > arr[greatest])


greatest = leftSide;

if (rightSide < n && arr[rightSide] > arr[greatest])


greatest = rightSide;

// Swap and continue heapifying if the root is not the greatest


if (greatest != i) {
swap(&arr[i], &arr[greatest]);
heapify(arr, n, greatest);
}
}

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

// Printing the array


void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}

Complexity of the Heap Sort Algorithm

To sort an unsorted list with 'n' number of elements, following are the complexities...

Worst Case : O(n log n)

Best Case : O(n log n)

Average Case : O(n log n)

Binary Search tree

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.

Now, let's start the topic, the Binary Search tree.

What is a Binary Search tree?

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.

Let's understand the concept of Binary search tree with an example.

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.

Advantages of 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.

Example of creating a binary search tree

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 -

Step 1 - Insert 45.

Step 2 - Insert 15.

As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.

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.

Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

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.

Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.

Step 9 - Insert 50.


50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree
of 55.

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.

Let's understand how a search is performed on a binary search tree.

Searching in Binary search tree

Searching means to find or locate a specific element or node in a data structure. In


Binary search tree, searching a node is easy because elements in BST are stored in a
specific order. The steps of searching a node in Binary Search tree are listed as follows
-

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.

5. Repeat the above procedure recursively until the match is found.


6. If the element is not found or not present in the tree, then return NULL.

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.

Algorithm to search an element in Binary search tree

1. Search (root, item)


2. Step 1 - if (item = root → data) or (root = NULL)
3. return root
4. else if (item < root → data)
5. return Search(root → left, item)
6. else
7. return Search(root → right, item)
8. END if
9. Step 2 - END

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 -

○ The node to be deleted is the leaf node, or,

○ The node to be deleted has only one child, and,

○ The node to be deleted has two children

We will understand the situations listed above in detail.

When the node to be deleted is the leaf node

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.

When the node to be deleted has only one child

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.

When the node to be deleted has two children

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 -

○ First, find the inorder successor of the node to be deleted.

○ 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.

Insertion in 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(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

Where 'n' is the number of nodes in the given tree.


2. Space Complexity

Operations Space complexity

Insertion O(n)

Deletion O(n)

Search O(n)

○ The space complexity of all operations of Binary search tree is O(n).

Height Of Binary Search Tree


To find the height of the binary search tree (height: no of nodes from leaf to root)
Int find_height(root)
{
if(root == null)
{
return -1;
}
Int left height = find_height(root—>left);
Int right height = find_height(root—>right);
If (left height > rightheight)
{
return ;leftheight + 1;
}
else
{
Return rightheight + 1;
}
}

You might also like