Data Structures Lab 10 Binary Search Trees
Data Structures Lab 10 Binary Search Trees
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
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.
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
Algorithms:
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:
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)
• 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.
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