0% found this document useful (0 votes)
20 views

Data Structures Lab 10 Binary Search Trees

Uploaded by

doravivek6
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Data Structures Lab 10 Binary Search Trees

Uploaded by

doravivek6
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Data Structures Lab 10

Binary Search Trees


Outline
• Introduction to Binary search trees.
• Algorithm for Binary search tree operations.
• Generating Binary search tree using traversals.
• Drawback for Binary search tree.
• Applications of Binary search tree.
• Exercise.
• Prelab questions.
Introduction - Binary Search Trees (BST)
 Binary Search Tree is a Binary tree with the following properties:
 Every element has a unique key. ( No Duplicates)
 The keys in a non-empty left sub-tree are smaller than the key in the root of sub-tree.
 The keys in a non-empty right sub-tree are larger than the key in the root of sub-tree.
 The left and right sub-trees are also binary search trees.
 Examples of Binary Search Trees: ( A BST may not be a complete binary tree)

 The tree below is not a BST:


Binary Search Trees (BST)
 In Binary Tree we did not impose any restriction on the data stored in the nodes data.
 As a result, to search for an element we need to check both in left sub-tree and in
right subtree.
 Due to this, the average case time complexity of search operation is very large.
 BST imposes restriction on the kind of data a node can contain. As a result, it reduces
the average case time complexity of search operation.
• Basic Operations:
– Inserting an element into a binary search tree
– Deleting element from a binary search tree
– Find/Search for an element
– Tree Traversals (same as in Binary Trees)
– Finding the Minimum and Maximum elements in a binary search tree
– Finding Successor and Predecessor of an element in BST
• Auxiliary Operations:
– Checking whether a tree is BST or not
– Find the Kth smallest element in a tree
– Sorting the elements in a BST : Inorder traversal of a BST gives the elements in
sorted order
BST – Search Operation

 To search a given key in Binary Search Tree:


 we first compare it with root, if the key is present at root, we return root.
 If key is greater than root’s key, we recur the search operation for right sub-tree of root node.
 Otherwise we recur the search operation for left sub-tree of root.
 If element to search is found anywhere, return true, else return false.

 Algorithm:
node* search(node *tree, int key)
{
if(!tree)
{
return NULL;
}
if(key < tree->data)
{
search(tree->left, key);
}
else if(key > tree->data)
{
search(tree->right, key);
}
else if(key == tree->data)
{
return tree;
}
}
BST – Insert Operation
 To insert a given key into Binary Search Tree:
 A new key is always inserted at leaf.
 We start searching a key from root till we hit a leaf node (move left is key is smaller, and right
if it is larger)
 Once a leaf node is found, the new node is added as a left child of the leaf node if it is
smaller than the leaf node / right child of the leaf node if it is larger than the leaf node.
 Algorithm:
node* insert(node *root, int key)
{
node* newNode = (node *)malloc(sizeof(node));
node->data=key;
node->left = node->right = NULL:
if (root == NULL) return newNode;
if (key < root->data)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
BST – Delete Operation
When we delete a node from BST, three possibilities arise:

1) Node to be deleted is leaf: Simply remove from the tree. Return NULL to its parent, i.e. make the
corresponding child pointer NULL

2) Node to be deleted has only one child: Copy the child key to the node and delete the child.
BST – Delete Operation

3) Node to be deleted has both children: There are two options

a) Find the Inorder successor of the node (Minimum value in the node’s right sub-tree), copy contents of the
Inorder successor to the node and delete the Inorder successor.

Inorder successor of 50 is 60 (minimum value if its right sub-tree)

b) Find the Inorder predecessor of the node (Maximum value in the node’s left sub-tree), copy contents of
The Inorder predecessor to the node and delete the Inorder predecessor.
BST – Delete Operation
struct Node *delete(struct Node *p,int key)
{
struct Node *q;
if(p==NULL) return NULL; //if the node to be deleted is the only node in the tree
if(p->lchild==NULL && p->rchild==NULL)
{
if(p==root) root=NULL;
free(p);
return NULL;
}
if(key<p->data)
p->lchild=delete(p->lchild,key); // If the key to be deleted is smaller than the root move to its left subtree

else if(key>p->data)
p->rchild=delete(p->rchild,key); // If the key to be deleted is larger than the root move to its right subtree
else { //If the key value is equal to the root, this is the node to be deleted
if(height(p->lchild)>height(p->rchild)) // calculate height of left and right subtree and replace the deleted node
with its inorder successor or predecessor
{
q=inpre(root,p);
p->data=q->data;
p->lchild=delete(p->lchild,q->data);
}
else{
q=insucc(root,p);
p->data=q->data;
p->rchild=delete(p->rchild,q->data);
}
}
return p;
}
BST – Find Minimum/ Maximum Key

 To find the maximum/minimum key in Binary Search Tree:


 we can find maximum by traversing right pointers until we reach rightmost node
 and the minimum by traversing left pointers until we reach leftmost node

 Algorithms:

int minKey(node* root)


{
node* temp = root;
while (temp->left != NULL) //find the leftmost leaf
{
temp = temp->left;
}
return(temp->data);
}

int maxKey(node* root)


{
node* temp = root;
while (temp->right != NULL) //find the rightmost leaf
{
temp = temp->right;
}
return(temp->data);
}
BST – Find Inorder Successor
 Inorder successor of a node is the next node in Inorder traversal of the Binary Search Tree
 In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key
greater than the key of input node.
 If right sub-tree of node is not NULL, then successor is the minimum key in the node’s right-subtree.
If right sub-tree of node is NULL, then start from root and use search like technique. Do the following:
Travel down the tree, if a node’s data is greater than root’s data then go right side, otherwise go to left side.
 Algorithm:
int Successor(node *root, node *n)
{
if(n->right != NULL ) // the minimum value in right sub-tree is successor
return minKey(n->right);
node *succ = NULL;
// Start from root and search for successor down the tree
while (root != NULL)
{
if (root->data > n->data)
{
succ = root;
root = root->left;
}
else if (root->data < n->data) {
succ = root;
root = root->right;
}
else
break;
}
return succ->data;
}
BST – Find Inorder Predecessor
 Inorder predecessor of a node is the previous node in Inorder traversal of the Binary Search Tree
 In Binary Search Tree, Inorder Predecessor of an input node can also be defined as the node with the largest key
smaller than the key of input node.
 If left sub-tree of node is not NULL, then predecessor is the maximum key in the node’s left-subtree.
If left sub-tree of node is NULL, then start from root and use search like technique.
 Algorithm:
int Predecessor(node *root, node *n)
{
if(n->left != NULL ) // the maximum value in left sub-tree is predecessor
return maxKey(n->left);
node *pred = NULL;
// Start from root and search for successor down the tree
while (root != NULL)
{
if (root->data > n->data)
{
pred = root;
root = root->left;
}
else if (root->data < n->data)
{
pred = root;
root = root->right;
}
else
break;
}
return pred->data;
}
Binary Search Tree: Exercise
• Construct a Binary Search Tree for the following elements :
11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31
Traverse the BST created in Preorder, Inorder and Post Order.

PreOrder : 11 6 4 5 8 10 19 17 43 32 49
Inorder: 4 5 6 8 10 11 17 19 31 43 49
PostOrder: 5 4 10 8 6 17 31 49 43 19 11
Binary Search Tree: Exercise
• Delete 11:

Option a: replace node 11 with inorder successor = minumum element in right


subtree = 17 and delete node 17

Option a: replace node 11 with inorder predecessor= maximum element in left


subtree = 10 and delete node 10

Find out height of left and right sub trees. Based on height which sub tree is having maximum
height replace the node accordingly with its inorder successor or inorder predecessor.
Binary Search Tree: Exercise
• Construct a Binary Search Tree for the following elements :
f, b, h, a, e, g, d, c
Traverse the BST created in Preorder, Inorder and Post Order.

PreOrder : f b a e d c h g
Inorder: a b c d e f g h
PostOrder: a c d e b g h f
Generating Binary Search Tree using Inorder and Postorder Traversals

• Construct a Binary Search Tree from given Inorder and Postorder Traversals:
Inorder: 1, 5, 7, 10, 40, 50
PostOrder: 1, 7, 5, 50, 40, 10
Any BST traversed in Inorder will be a sorted list in ascending order
Consider the Postorder traversal:
 The last element of postorder traversal is always root.
 We first construct the root.
 Then we find the index of last element which is smaller than root. Let the index be ‘i’.
 The values between 0 and ‘i’ are part of left subtree, and
 The values between ‘i+1’ and ‘n-2’ are part of right subtree.
 Divide given post[] at index “i” and recur for left and right sub-trees.
In {1, 7, 5, 40, 50, 10}, 10 is the last element, so we make it root. All elements in the postorder traversal
that are less than 10 go to its left and elements greater than 10 go to its right.

Now we recursively do the same for the next level. i.e We recursively follow above steps for subarrays
{1, 7, 5} and {50, 40}, and get the BST. So we know the structure of BST is as following.
Binary Search Tree: Exercise
• Example 2:
Inorder: 2 3 5 7 9 10 11 12
PostOrder: 2 5 3 9 11 12 10 7
Solution:
Generating Binary Search Tree using Inorder and Preorder Traversals
• Construct a Binary Search Tree from given Inorder and PreorderTraversals:
Inorder: 1, 5, 7, 10, 40, 50
Preorder: 10, 5, 1, 7, 40, 50
Any BST traversed in Inorder will be a sorted list in ascending order
Consider the Preorder traversal:
 The first element of preorder traversal is always root .We first construct the root.
 Then we find the index of first element which is greater than root. Let the index be ‘i’.
 The values between root and ‘i’ will be part of left subtree, and
 The values between ‘i+1’ and ‘n-1’ will be part of right subtree
 Divide given pre[] at index “i” and recur for left and right sub-trees.
In {10, 5, 1, 7, 40, 50}, 10 is the first element, so we make it root. Now we look for the first element greater than 10,
we find 40. So we know the structure of BST is as following.

Now we recursively do the same for the next level. i.e We recursively follow above steps for sub-arrays
{5, 1, 7} and {40, 50} and get the BST. So we know the structure of BST is as following.
Binary Search Tree: Exercise
• Example 2:
Inorder: 1,5,7,10,15,20,25,30,32,35,40
PreOrder: 20, 10, 5, 1, 7, 15, 30, 25, 35, 32, 40
Solution:

Recursively continuing for the next level, we get the final tree as:
Generating Binary Search Tree using preorder traversals
For a BST tree can be generated using combination of two traversal techniques like
Preorder+Inorder or Postorder+Inorder and construct BST like generated for Binary tree.
Even for BST if only preorder or postorder is given with the help of that we can build a BST taking
help of stack data structure.
Example: PreOrder: 20, 10, 5, 1, 7, 15, 30, 25, 35, 32, 40

Procedure:
1) Create an empty stack.
2) Make the first value as root. Push it to the stack.
3) Keep on popping while the stack is not empty and the next value is greater than stack’s top
value. Make this value as the right child of the last popped node. Push the new node to the
stack.
4) If the next value is less than the stack’s top value, make this value as the left child of the
stack’s top node. Push the new node to the stack.
5) Repeat steps 2 and 3 until there are items remaining in pre[].
Time Complexities
• Assuming height of a BST to become as large as ‘n’ for given n elements in
worst case ( if the elements are given in ascending ir descending order) the
time complexities are:
Algorithm Average Worst case
Search O(log n) O(n)

Insert O(log n) O(n)

Delete O(log n) O(n)


Applications of BST
• It is used to implement dictionary.
• It is used to implement multilevel indexing in DATABASE.
• To implement Huffman Coding Algorithm.
• It is used to implement searching Algorithm.
Drawback for Binary Search Tree
• Consider the keys: 4, 2 , 3, 1, 5, 6 and the BST is as follows:
• Where height is 2 and it is a balanced Binary search tree with time complexity O(log n).

• Now consider the same keys with different order:


1, 2, 3, 4, 5, 6
• Where height is 5 and it is a unbalanced BST with complexity O(n)

• So, here the height of a BST can be as minimum of log n and as maximum of n and it
depends on how we are inserting the keys. But we cannot control on order of insertion
to the user. So it is difficult to control the height of a BST which is drawback for BST and
can be resolved by AVL trees.
Exercise
1) Write a menu driven program for implementation of operations on a Binary
search Tree.
The operations include:
a) Create b) Insert c) Delete d) Search e) InOrder Traversal
Prelab questions
1) From a give binary tree
Circle all the leaves. Put a square box around the root. Draw a star around each ancestor of the node that contains
10. Put a big X through every descendant of the node the contains 10.

2) From the given binary search tree


Give the inorder successor and inorder predecessor for nodes 16,4,1,14

3) Give the procedure to find least common ancestor (LCA) of two nodes in a Binary Search Tree.
• Reference link for practice:
Virtual labs: https://ds1-iiith.vlabs.ac.in/exp/binary-search-trees/exp.html#Analysis
https://medium.com/techie-delight
/binary-search-tree-bst-practice-problems-and-interview-questions-ea13a6731098

You might also like