0% found this document useful (0 votes)
129 views48 pages

Binary Tree and BST

A binary tree is a hierarchical data structure where each node has at most two children. Each node contains data and pointers to its left and right children. There are different types of binary trees such as rooted binary trees where there is a distinct root node, full binary trees where every node has 0 or 2 children, complete binary trees where all levels are fully filled except the last, and skewed binary trees where one node has no children. Binary trees can be traversed using preorder, inorder, and postorder traversal techniques.

Uploaded by

sri aknth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views48 pages

Binary Tree and BST

A binary tree is a hierarchical data structure where each node has at most two children. Each node contains data and pointers to its left and right children. There are different types of binary trees such as rooted binary trees where there is a distinct root node, full binary trees where every node has 0 or 2 children, complete binary trees where all levels are fully filled except the last, and skewed binary trees where one node has no children. Binary trees can be traversed using preorder, inorder, and postorder traversal techniques.

Uploaded by

sri aknth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Binary Tree-

Binary tree is a special tree data structure in which each node can have at most 2
children.
Thus, in a binary tree,
Each node has either 0 child or 1 child or 2 children.

Example-

Unlabeled Binary Tree-


A binary tree is unlabeled if its nodes are not assigned any label.
Example-
Consider we want to draw all the binary trees possible with 3 unlabeled nodes.
Using the above formula, we have-
Number of binary trees possible with 3 unlabeled nodes
= 2 x 3C3 / (3 + 1)
= 6C3 / 4
=5
Thus,
 With 3 unlabeled nodes, 5 unlabeled binary trees are possible.
 These unlabeled binary trees are as follows-

Labeled Binary Tree-


A binary tree is labeled if all its nodes are assigned a label.
Example-
Consider we want to draw all the binary trees possible with 3 labeled nodes.
Using the above formula, we have-
Number of binary trees possible with 3 labeled nodes
= { 2 x 3C3 / (3 + 1) } x 3!
= { 6C3 / 4 } x 6
=5x6
= 30
Thus,
 With 3 labeled nodes, 30 labeled binary trees are possible.
 Each unlabeled structure gives rise to 3! = 6 different labeled structures.

Similarly,
 Every other unlabeled structure gives rise to 6 different labeled structures.
 Thus, in total 30 different labeled binary trees are possible.
Types of Binary Trees-
Binary trees can be of the following types-

1. Rooted Binary Tree


2. Full / Strictly Binary Tree
3. Complete / Perfect Binary Tree
4. Almost Complete Binary Tree
5. Skewed Binary Tree
1. Rooted Binary Tree-
A rooted binary tree is a binary tree that satisfies the following 2 properties-
 It has a root node.
 Each node has at most 2 children.
Example-

2. Full / Strictly Binary Tree-


 A binary tree in which every node has either 0 or 2 children is called as a Full binary
tree.
 Full binary tree is also called as Strictly binary tree.
Example-

Here,
 First binary tree is not a full binary tree.
 This is because node C has only 1 child.

3. Complete / Perfect Binary Tree-


A complete binary tree is a binary tree that satisfies the following 2 properties-
 Every internal node has exactly 2 children.
 All the leaf nodes are at the same level.
Complete binary tree is also called as Perfect binary tree.

Example-

Here,
 First binary tree is not a complete binary tree.
 This is because all the leaf nodes are not at the same level.

4. Almost Complete Binary Tree-


An almost complete binary tree is a binary tree that satisfies the following 2 properties-
 All the levels are completely filled except possibly the last level.
 The last level must be strictly filled from left to right.
Example-

Here,
 First binary tree is not an almost complete binary tree.
 This is because the last level is not filled from left to right.

5. Skewed Binary Tree-


A skewed binary tree is a binary tree that satisfies the following 2 properties-
 All the nodes except one node has one and only one child.
 The remaining node has no child.
OR
A skewed binary tree is a binary tree of n nodes such that its depth is (n-1).

Example-

Binary Tree Properties-


Important properties of binary trees are-

Property-01:
Minimum number of nodes in a binary tree of height H
=H+1
Example-
To construct a binary tree of height = 4, we need at least 4 + 1 = 5 nodes.

Property-02:

Maximum number of nodes in a binary tree of height H


= 2H+1 – 1

Example-
Maximum number of nodes in a binary tree of height 3
= 23+1 – 1
= 16 – 1
= 15 nodes
Thus, in a binary tree of height = 3, maximum number of nodes that can be inserted = 15.

We can not insert more number of nodes in this binary tree.


Property-03:
Total Number of leaf nodes in a Binary Tree
= Total Number of nodes with 2 children + 1

Example-
Consider the following binary tree-

Here,
 Number of leaf nodes = 3
 Number of nodes with 2 children = 2
Clearly, number of leaf nodes is one greater than number of nodes with 2 children.
This verifies the above relation.

NOTE
It is interesting to note that-
Number of leaf nodes in any binary tree depends only on the number of nodes with 2
children.

Property-04:
Maximum number of nodes at any level ‘L’ in a binary tree
= 2L

Example-
Maximum number of nodes at level-2 in a binary tree
= 22
=4
Thus, in a binary tree, maximum number of nodes that can be present at level-2 = 4.
Tree Traversal-
Tree Traversal refers to the process of visiting each node in a tree data structure exactly
once.

Various tree traversal techniques are-

Depth First Traversal-


Following three traversal techniques fall under Depth First Traversal-
1. Preorder Traversal
2. Inorder Traversal
3. Postorder Traversal
1. Preorder Traversal-
Algorithm-
Visit the root
1. Traverse the left sub tree i.e. call Preorder (left sub tree)
2. Traverse the right sub tree i.e. call Preorder (right sub tree)

Root → Left → Right


Example-
Consider the following example-

Applications-
 Preorder traversal is used to get prefix expression of an expression tree.
 Preorder traversal is used to create a copy of the tree.
2. Inorder Traversal-
Algorithm-
Traverse the left sub tree i.e. call Inorder (left sub tree)
1. Visit the root
2. Traverse the right sub tree i.e. call Inorder (right sub tree)

Left → Root → Right

Example-
Consider the following example-
Application-
 Inorder traversal is used to get infix expression of an expression tree.

3. Postorder Traversal-
Algorithm-
1. Traverse the left sub tree i.e. call Postorder (left sub tree)
2. Traverse the right sub tree i.e. call Postorder (right sub tree)
3. Visit the root
Left → Right → Root

Example-
Consider the following example-

Applications-
 Postorder traversal is used to get postfix expression of an expression tree.
 Postorder traversal is used to delete the tree.
 This is because it deletes the children first and then it deletes the parent.

Breadth First Traversal-

 Breadth First Traversal of a tree prints all the nodes of a tree level by level.
 Breadth First Traversal is also called as Level Order Traversal.
Example-

Application-
 Level order traversal is used to print the data in the same order as stored in the array
representation of a complete binary tree.

PRACTICE PROBLEMS BASED ON TREE


TRAVERSAL-
Problem-01:

If the binary tree in figure is traversed in inorder, then the order in which the nodes will be
visited is ____?

Solution-
The inorder traversal will be performed as-
Problem-02:
Which of the following sequences denotes the postorder traversal sequence of the tree
shown in figure?

1. FEGCBDBA
2. GCBDAFE
3. GCDBFEA
4. FDEGCBA

Problem-03:

Let LASTPOST, LASTIN, LASTPRE denote the last vertex visited in a postorder, inorder
and preorder traversal respectively of a complete binary tree. Which of the following is
always true?
1. LASTIN = LASTPOST
2. LASTIN = LASTPRE
3. LASTPRE = LASTPOST
4. None of these

Solution-
Consider the following complete binary tree-
Preorder Traversal : B , A , E
Inorder Traversal :B,A,E
Postorder Traversal : B , E , A

Clearly, LASTIN = LASTPRE.


Thus, Option (B) is correct.

Problem-04:
Which of the following binary trees has its inorder and preorder traversals as BCAD and
ABCD respectively-

Solution-
Option (D) is correct
6/17/2021 Binary Tree and its Types | Data Structure Tutorial | Studytonight

Introduction To Binary Trees

A binary tree is a hierarchical data structure in which each node has at most two children generally referred as left child and right child.

Each node contains three components:

1. Pointer to left subtree


2. Pointer to right subtree
3. Data element

The topmost node in the tree is called the root. An empty tree is represented by NULL pointer.

A representation of binary tree is shown:

Binary Tree: Common Terminologies

Root: Topmost node in a tree.


Parent: Every node (excluding a root) in a tree is connected by a directed edge from exactly one other node. This node is called a
parent.
Child: A node directly connected to another node when moving away from the root.
Leaf/External node: Node with no children.
Internal node: Node with atleast one children.
Depth of a node: Number of edges from root to the node.
Height of a node: Number of edges from the node to the deepest leaf. Height of the tree is the height of the root.

https://www.studytonight.com/data-structures/introduction-to-binary-trees 1/4
6/17/2021 Binary Tree and its Types | Data Structure Tutorial | Studytonight

In the above binary tree we see that root node is A. The tree has 10 nodes with 5 internal nodes, i.e, A,B,C,E,G and 5 external nodes,
i.e, D,F,H,I,J. The height of the tree is 3. B is the parent of D and E while D and E are children of B.

Advantages of Trees
Trees are so useful and frequently used, because they have some very serious advantages:

Trees reflect structural relationships in the data.


Trees are used to represent hierarchies.
Trees provide an efficient insertion and searching.
Trees are very flexible data, allowing to move subtrees around with minumum effort.

Types of Binary Trees (Based on Structure)

Rooted binary tree: It has a root node and every node has atmost two children.
Full binary tree: It is a tree in which every node in the tree has either 0 or 2 children.

The number of nodes, n, in a full binary tree is atleast n = 2h – 1, and atmost n = 2h+1 – 1, where h is the height of the tree.
The number of leaf nodes l, in a full binary tree is number, L of internal nodes + 1, i.e, l = L+1.
Perfect binary tree: It is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level.

https://www.studytonight.com/data-structures/introduction-to-binary-trees 2/4
6/17/2021 Binary Tree and its Types | Data Structure Tutorial | Studytonight

A perfect binary tree with l leaves has n = 2l-1 nodes.


In perfect full binary tree, l = 2h and n = 2h+1 - 1 where, n is number of nodes, h is height of tree and l is number of leaf nodes
Complete binary tree: It is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far
left as possible.

The number of internal nodes in a complete binary tree of n nodes is floor(n/2).


Balanced binary tree: A binary tree is height balanced if it satisfies the following constraints:
1. The left and right subtrees' heights differ by at most one, AND
2. The left subtree is balanced, AND
3. The right subtree is balanced

An empty tree is height balanced.

https://www.studytonight.com/data-structures/introduction-to-binary-trees 3/4
6/17/2021 Binary Tree and its Types | Data Structure Tutorial | Studytonight

The height of a balanced binary tree is O(Log n) where n is number of nodes.


Degenarate tree: It is a tree is where each parent node has only one child node. It behaves like a linked list.

https://www.studytonight.com/data-structures/introduction-to-binary-trees 4/4
6/28/2021 Binary Tree Traversal | Inorder, Preorder and Postorder

Binary Tree Traversal | Inorder,


Preorder and Postorder
Published on 07 Mar 2020

Binary tree traversal can be done in the following ways.


Inorder traversal
Preorder traversal
Postorder traversal

Consider the given binary tree,

         

 
Inorder Traversal: 7 9 4 2 5 1 3 6 8
Preorder Traversal: 1 2 4 7 9 5 3 6 8
Postorder Traversal: 9 7 4 5 2 8 6 3 1
 
Inorder Traversal:  For binary search trees (BST), Inorder Traversal specifies the nodes in non-
descending order. In order to obtain nodes from BST in non-increasing order, a variation of inorder
traversal may be used where inorder traversal is reversed.

https://www.faceprep.in/data-structures/tree-traversals-inorder-preorder-and-postorder/ 1/5
6/28/2021 Binary Tree Traversal | Inorder, Preorder and Postorder

Preorder Traversal: Preorder traversal will create a copy of the tree. Preorder Traversal is also used
to get the prefix expression of an expression.

Postorder Traversal: Postorder traversal is used to get the postfix expression of an expression given
 

Algorithm for binary tree traversal


Inorder(root)
Traverse the left sub-tree, (recursively call inorder(root -> left).
Visit and print the root node.
Traverse the right sub-tree, (recursively call inorder(root -> right).

Preorder(root)
Visit and print the root node.
Traverse the left sub-tree, (recursively call inorder(root -> left).
Traverse the right sub-tree, (recursively call inorder(root -> right).

Postorder(root)
Traverse the left sub-tree, (recursively call inorder(root -> left).
Traverse the right sub-tree, (recursively call inorder(root -> right).
Visit and print the root node.

Program for binary tree traversals in inorder, preorder, and postorder traversals is given below.

https://www.faceprep.in/data-structures/tree-traversals-inorder-preorder-and-postorder/ 2/5
6/28/2021 Binary Tree Traversal | Inorder, Preorder and Postorder

#include <iostream>

#include <stdlib.h>

using namespace std;

/* Structure for a node */

struct node

int data;

struct node *left;

struct node *right;

};

/* Function to create a new node */

struct node *newNode(int data)

struct node *temp = (struct node *) malloc(sizeof(struct node));

temp -> data = data;

temp -> left = NULL;

temp -> right = NULL;

return temp;

};

/* Function to insert a node in the tree */

void insert_node(struct node *root, int n1, int n2, char lr)

if(root == NULL)

return;

if(root -> data == n1)

switch(lr)

case 'l' :root -> left = newNode(n2);

break;

case 'r' : root -> right = newNode(n2);

break;

else

insert_node(root -> left, n1, n2, lr);

insert_node(root -> right, n1, n2, lr);

/* Function to print the inorder traversal of the tree */

void inorder(struct node *root)

if(root == NULL)

return;

inorder(root -> left);

cout << root -> data << " ";

inorder(root -> right);

https://www.faceprep.in/data-structures/tree-traversals-inorder-preorder-and-postorder/ 3/5
6/28/2021 Binary Tree Traversal | Inorder, Preorder and Postorder

/* Function to print the preorder traversal of the tree */

void preorder(struct node *root)

if(root == NULL)

return;

cout << root -> data << " ";

preorder(root -> left);

preorder(root -> right);

/* Function to print the postorder traversal of the tree */

void postorder(struct node *root)

if(root == NULL)

return;

postorder(root -> left);

postorder(root -> right);

cout << root -> data << " ";

/* Main Function */

int main()

struct node *root = NULL;

int n;

cout <<"\nEnter the number of edges : ";

cin >> n;

cout << "\nInput the nodes of the binary tree in order \n\nparent-child-left(or)right-\n\n";

while(n--)

char lr;

int n1,n2;

cin >> n1 >> n2;

cin >>lr;

if(root == NULL)

root = newNode(n1);

switch(lr)

case 'l' :root -> left = newNode(n2);

break;

case 'r' : root -> right = newNode(n2);

break;

else

insert_node(root,n1,n2,lr);

cout <<"\nInorder Traversal : ";

inorder(root);

cout << endl;

https://www.faceprep.in/data-structures/tree-traversals-inorder-preorder-and-postorder/ 4/5
6/28/2021 Binary Tree Traversal | Inorder, Preorder and Postorder

cout <<"\nPreorder Traversal : ";

preorder(root);

cout << endl;

cout <<"\nPostorder Traversal : ";

postorder(root);

cout << endl;

return 0;

https://www.faceprep.in/data-structures/tree-traversals-inorder-preorder-and-postorder/ 5/5
Binary Search Tree-

Binary Search Tree is a special kind of binary tree in which nodes are arranged in a
specific order.

In a binary search tree (BST), each node contains-


 Only smaller values in its left sub tree
 Only larger values in its right sub tree

Example-

Number of Binary Search Trees-


Example-

Number of distinct binary search trees possible with 3 distinct keys


= 2×3C3 / 3+1
= 6C3 / 4
=5

If three distinct keys are A, B and C, then 5 distinct binary search trees are-

Binary Search Tree Construction-

Let us understand the construction of a binary search tree using the following example-

Example-

Construct a Binary Search Tree (BST) for the following sequence of numbers-
50, 70, 60, 20, 90, 10, 40, 100
When elements are given in a sequence,
 Always consider the first element as the root node.
 Consider the given elements and insert them in the BST one by one.

The binary search tree will be constructed as explained below-


Insert 50-

Insert 70-
 As 70 > 50, so insert 70 to the right of 50.

Insert 60-
 As 60 > 50, so insert 60 to the right of 50.
 As 60 < 70, so insert 60 to the left of 70.

Insert 20-
 As 20 < 50, so insert 20 to the left of 50.

Insert 90-
 As 90 > 50, so insert 90 to the right of 50.
 As 90 > 70, so insert 90 to the right of 70.
Insert 10-
 As 10 < 50, so insert 10 to the left of 50.
 As 10 < 20, so insert 10 to the left of 20.

Insert 40-
 As 40 < 50, so insert 40 to the left of 50.
 As 40 > 20, so insert 40 to the right of 20.

Insert 100-
 As 100 > 50, so insert 100 to the right of 50.
 As 100 > 70, so insert 100 to the right of 70.
 As 100 > 90, so insert 100 to the right of 90.
This is the required Binary Search Tree.

PRACTICE PROBLEMS BASED ON BINARY SEARCH


TREES-
Problem-01:

A binary search tree is generated by inserting in order of the following integers-


50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24
The number of nodes in the left subtree and right subtree of the root respectively is _____.
1. (4, 7)
2. (7, 4)
3. (8, 3)
4. (3, 8)
Solution-
Using the above discussed steps, we will construct the binary search tree.
The resultant binary search tree will be-
Clearly,
 Number of nodes in the left subtree of the root = 7
 Number of nodes in the right subtree of the root = 4
Thus, Option (B) is correct.

Problem-02:
How many distinct binary search trees can be constructed out of 4 distinct keys?
1. 5
2. 14
3. 24
4. 35
Solution-
Number of distinct binary search trees possible with 4 distinct keys
= 2nCn / n+1
= 2×4C4 / 4+1
= 8C4 / 5
= 14
Thus, Option (B) is correct.
Binary Search Tree Operations-
Commonly performed operations on binary search tree are-

1. Search Operation
2. Insertion Operation
3. Deletion Operation
1. Search Operation-

Search Operation is performed to search a particular element in the Binary Search Tree.

Rules-
For searching a given key in the BST,
 Compare the key with the value of root node.
 If the key is present at the root node, then return the root node.
 If the key is greater than the root node value, then recur for the root node’s right subtree.
 If the key is smaller than the root node value, then recur for the root node’s left subtree.
Example-
Consider key = 45 has to be searched in the given BST-
We start our search from the root node 25.
 As 45 > 25, so we search in 25’s right subtree.
 As 45 < 50, so we search in 50’s left subtree.
 As 45 > 35, so we search in 35’s right subtree.
 As 45 > 44, so we search in 44’s right subtree but 44 has no subtrees.
 So, we conclude that 45 is not present in the above BST.

2. Insertion Operation-
Insertion Operation is performed to insert an element in the Binary Search Tree.

Rules-
The insertion of a new key always takes place as the child of some leaf node.
For finding out the suitable leaf node,
 Search the key to be inserted from the root node till some leaf node is reached.
 Once a leaf node is reached, insert the key as child of that leaf node.

Example-

Consider the following example where key = 40 is inserted in the given BST-

 We start searching for value 40 from the root node 100.


 As 40 < 100, so we search in 100’s left subtree.
 As 40 > 20, so we search in 20’s right subtree.
 As 40 > 30, so we add 40 to 30’s right subtree.
3. Deletion Operation-
Deletion Operation is performed to delete a particular element from the Binary Search Tree.

When it comes to deleting a node from the binary search tree, following three cases are
possible-

Case-01: Deletion Of A Node Having No Child (Leaf Node)-


Just remove / disconnect the leaf node that is to deleted from the tree.

Example-
Consider the following example where node with value = 20 is deleted from the BST-

Case-02: Deletion Of A Node Having Only One Child-


Just make the child of the deleting node, the child of its grandparent.

Example-
Consider the following example where node with value = 30 is deleted from the BST-

Case-02: Deletion Of A Node Having Two Children-


A node with two children may be deleted from the BST in the following two ways-

Method-01:
 Visit to the right subtree of the deleting node.
 Pluck the least value element called as inorder successor.
 Replace the deleting element with its inorder successor.
Example-
Consider the following example where node with value = 15 is deleted from the BST-

Method-02:
 Visit to the left subtree of the deleting node.
 Pluck the greatest value element called as inorder predecessor.
 Replace the deleting element with its inorder predecessor.
Example-
Consider the following example where node with value = 15 is deleted from the BST-

Time Complexity-
Time complexity of all BST Operations = O(h).
 Here, h = Height of binary search tree
Now, let us discuss the worst case and best case.

Worst Case-
In worst case,
 The binary search tree is a skewed binary search tree.
 Height of the binary search tree becomes n.
 So, Time complexity of BST Operations = O(n).
In this case, binary search tree is as good as unordered list with no benefits.

Best Case-
In best case,
 The binary search tree is a balanced binary search tree.
 Height of the binary search tree becomes log(n).
 So, Time complexity of BST Operations = O(logn).

Example-
Consider the following binary search tree-

Now, let us write the traversal sequences for this binary search tree-
Preorder Traversal-
100, 20 , 10 , 30 , 200 , 150 , 300
Inorder Traversal-
10, 20 , 30 , 100 , 150 , 200 , 300
Postorder Traversal-
10, 30, 20, 150, 300 , 200 , 100

/*Binary Search Tree*/


#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *create(int ele)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=ele;
newnode->left=NULL;
newnode->right=NULL;
}
struct node *insert(struct node *root, int x)
{
if(root==NULL)
return create(x);
else if(x>root->data)
root->right=insert(root->right, x);
else
root->left=insert(root->left, x);
}
int search(struct node *root, int x)
{
while(root!=NULL)
{
if(root->data==x)
return 1;
else if(x>root->data)
root=root->right;
else if(x<root->data)
root=root->left;
}
return 0;
}
struct node *find_min(struct node *root)
{
if(root==NULL)
return NULL;
else if((root->left)!=NULL)
return find_min(root->left);
return root;
}
struct node *delete(struct node *root,int x)
{
if(root==NULL)
return NULL;
else if(x>root->data)
root->right=delete(root->right,x);
else if(x<root->data)
root->left=delete(root->left,x);
else
{
if(root->left==NULL&&root->right==NULL)
{
free(root);
return NULL;
}
else if(root->left==NULL||root->right==NULL)
{
struct node *temp;
if(root->left==NULL)
temp=root->right;
else
temp=root->left;
free(root);
return temp;
}
else
{
struct node *temp=find_min(root->right);
root->data=temp->data;
root->right=delete(root->right,temp->data);
}
}
return root;
}

void inorder(struct node *root)


{
if(root!=NULL)
{
inorder(root->left);
printf("%d\t",root->data);
inorder(root->right);
}
}
void preorder(struct node *root)
{
if(root!=NULL)
{
printf("%d\t",root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t",root->data);
}
}
int main()
{
struct node *root=NULL;
int ch,ele,root1=0;
while(1)
{
printf("\n1-insert\n2-delete\n3-inorder\n4-preorder\n5-postorder\n6-search\nAny other
option to exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf(“enter element : “);
scanf("%d",&ele);
root=insert(root,ele);
break;

case 2:printf("enter element to delete: ");


scanf("%d",&ele);
root=delete(root,ele);
break;
case 3:inorder(root);
break;
case 4:preorder(root);
break;
case 5:postorder(root);
break;
case 6:printf("enter ele\n");
scanf("%d",&ele);
root1=search(root,ele);
if(root1==1)
printf("element found\n");
if(root1==0)
printf("element not found\n");
break;
default:exit(1);
}
}
return 0;
}
8/16/2021 Binary Search Tree - javatpoint

Binary Search Tree


1. Binary Search tree can be defined as a class of binary trees, in which the nodes are arranged in
a specific order. This is also called ordered binary tree.

2. In a binary search tree, the value of all the nodes in the left sub-tree is less than the value of
the root.

3. Similarly, value of all the nodes in the right sub-tree is greater than or equal to the value of the
root.

4. This rule will be recursively applied to all the left and right sub-trees of the root.

A Binary search tree is shown in the above figure. As the constraint applied on the BST, we can see
that the root node 30 doesn't contain any value greater than or equal to 30 in its left sub-tree and it
also doesn't contain any value less than 30 in its right sub-tree.

Advantages of using binary search tree

https://www.javatpoint.com/binary-search-tree 1/8
8/16/2021 Binary Search Tree - javatpoint

1. Searching become very efficient in a binary search tree since, we get a hint at each step, about
which sub-tree contains the desired element.

2. The binary search tree is considered as efficient data structure in compare to arrays and linked
lists. In searching process, it removes half sub-tree at every step. Searching for an element in a
binary search tree takes o(log2n) time. In worst case, the time it takes to search an element is
0(n).

3. It also speed up the insertion and deletion operations as compare to that in array and linked
list.

Q. Create the binary search tree using the following data elements.

43, 10, 79, 90, 12, 54, 11, 9, 50

1. Insert 43 into the tree as the root of the tree.

2. Read the next element, if it is lesser than the root node element, insert it as the root of the left
sub-tree.

3. Otherwise, insert it as the root of the right of the right sub-tree.

The process of creating BST by using the given elements, is shown in the image below.

https://www.javatpoint.com/binary-search-tree 2/8
8/16/2021 Binary Search Tree - javatpoint

Operations on Binary Search Tree


There are many operations which can be performed on a binary search tree.

https://www.javatpoint.com/binary-search-tree 3/8
8/16/2021 Binary Search Tree - javatpoint

SN Operation Description

1 Searching Finding the location of some specific element in a binary search tree.
in BST

2 Insertion in Adding a new element to the binary search tree at the appropriate location so
BST that the property of BST do not violate.

3 Deletion in Deleting some specific node from a binary search tree. However, there can be
BST various cases in deletion depending upon the number of children, the node
have.

Program to implement BST operations

#include <iostream>  
#include <stdlib.h>  
using namespace std;  
struct Node {  
    int data;  
    Node *left;  
    Node *right;  
};  
Node* create(int item)  
{  
    Node* node = new Node;  
    node->data = item;  
    node->left = node->right = NULL;  
    return node;  
}  
  
void inorder(Node *root)  
{  
    if (root == NULL)  
        return;  
https://www.javatpoint.com/binary-search-tree 4/8
8/16/2021 Binary Search Tree - javatpoint

  
    inorder(root->left);  
    cout<< root->data << "   ";  
    inorder(root->right);  
}  
Node* findMinimum(Node* cur)  
{  
    while(cur->left != NULL) {  
        cur = cur->left;  
    }  
    return cur;  
}  
Node* insertion(Node* root, int item)  
{  
    if (root == NULL)  
        return create(item);  
    if (item < root->data)  
        root->left = insertion(root->left, item);  
    else  
        root->right = insertion(root->right, item);  
  
    return root;  
}  
  
void search(Node* &cur, int item, Node* &parent)  
{  
    while (cur != NULL && cur->data != item)  
    {  
        parent = cur;  
  
        if (item < cur->data)  
            cur = cur->left;  
        else  
            cur = cur->right;  
    }  
}  

https://www.javatpoint.com/binary-search-tree 5/8
8/16/2021 Binary Search Tree - javatpoint

  
void deletion(Node*& root, int item)  
{  
    Node* parent = NULL;  
    Node* cur = root;  
  
    search(cur, item, parent);  
    if (cur == NULL)  
        return;  
  
    if (cur->left == NULL && cur->right == NULL)  
    {  
        if (cur != root)  
        {  
            if (parent->left == cur)  
                parent->left = NULL;  
            else  
                parent->right = NULL;  
        }  
        else  
            root = NULL;  
  
        free(cur);       
    }  
    else if (cur->left && cur->right)  
    {  
        Node* succ  = findMinimum(cur- >right);  
  
        int val = succ->data;  
  
        deletion(root, succ->data);  
  
        cur->data = val;  
    }  
  
    else  

https://www.javatpoint.com/binary-search-tree 6/8
8/16/2021 Binary Search Tree - javatpoint

    {  
        Node* child = (cur->left)? Cur- >left: cur->right;  
  
        if (cur != root)  
        {  
            if (cur == parent->left)  
                parent->left = child;  
            else  
                parent->right = child;  
        }  
  
        else  
            root = child;  
        free(cur);  
    }  
}  
  
int main()  
{  
   Node* root = NULL;  
   int keys[8];  
   for(int i=0;i<8;i++)  
    {  
    cout << "Enter value to be inserted";  
    cin>>keys[i];  
        root = insertion(root, keys[i]);  
    }  
  
    inorder(root);  
    cout<<"\n";  
    deletion(root, 10);  
    inorder(root);  
    return 0;  
}  

Output:

https://www.javatpoint.com/binary-search-tree 7/8
8/16/2021 Binary Search Tree - javatpoint

Enter value to be inserted? 10

Enter value to be inserted? 20

Enter value to be inserted? 30

Enter value to be inserted? 40

Enter value to be inserted? 5

Enter value to be inserted? 25

Enter value to be inserted? 15

Enter value to be inserted? 5

5 5 10 15 20 25 30 40
5 5 15 20 25 30 40

https://www.javatpoint.com/binary-search-tree 8/8
8/17/2021 Deletion in Binary Search Tree - javatpoint

Deletion
Delete function is used to delete the specified node from a binary search tree. However, we must
delete a node from a binary search tree in such a way, that the property of binary search tree doesn't
violate. There are three situations of deleting a node from binary search tree.

The node to be deleted is a leaf node


It is the simplest case, in this case, replace the leaf node with the NULL and simple free the allocated
space.

In the following image, we are deleting the node 85, since the node is a leaf node, therefore the
node will be replaced with NULL and allocated space will be freed.

The node to be deleted has only one child.


In this case, replace the node with its child and delete the child node, which now contains the value
which is to be deleted. Simply replace it with the NULL and free the allocated space.

In the following image, the node 12 is to be deleted. It has only one child. The node will be replaced
with its child node and the replaced node 12 (which is now leaf node) will simply be deleted.

https://www.javatpoint.com/deletion-in-binary-search-tree 1/2
8/17/2021 Deletion in Binary Search Tree - javatpoint

The node to be deleted has two children.


It is a bit complexed case compare to other two cases. However, the node which is to be deleted, is
replaced with its in-order successor or predecessor recursively until the node value (to be deleted) is
placed on the leaf of the tree. After the procedure, replace the node with NULL and free the
allocated space.

In the following image, the node 50 is to be deleted which is the root node of the tree. The in-order
traversal of the tree given below.

6, 25, 30, 50, 52, 60, 70, 75.

replace 50 with its in-order successor 52. Now, 50 will be moved to the leaf of the tree, which will
simply be deleted.

https://www.javatpoint.com/deletion-in-binary-search-tree 2/2

You might also like