Binary Search Tree
Binary Search Tree
• Here,
• Root node: 8
• Left subtree (3): values < 8
• Right subtree (10): values > 8
• Each subtree maintains the
same rule, with values relative
to their respective roots.
Traversals in BST
• BST Traversal as same as Binary Tree Traversal
• Inorder
• Preorder
• Postorder
Creation of BST in Python
• Create a class Tree
• In the parameterized constructor, we have the default
parameter val = None
• When the Tree class is instantiated without any
parameter then it creates an empty node with left and
right pointers
• If we pass the value while instantiating then it creates a
node having that value and left, right pointers are
created with None Types.
Operations
• Insertion
• Deletion
• Searching
Inserting an element
1. Start from root.
2. Compare the inserting element with root, if less than root,
then recurse for left, else recurse for right.
3. After reaching end, just insert that node at left(if less than
current) else right.
Inserting 4
Searching an element
1. Start from root.
2. Compare the searching element with root, if less
than root, then recurse for left, else recurse for
right.
3. If element to search is found anywhere, return true,
else return false.
Searching 6
Searching 4 from the below tree
If the value is not found, we eventually reach the left or right child of a leaf node
which is NULL and it gets propagated and returned.
Deletion
• Three cases
1) Node to be deleted is leaf
2) Node to be deleted has only one child
3) Node to be deleted has two children
1) Node to be deleted is leaf: Simply remove from the
tree.
2) Node to be deleted has only one child:
• Replace that node with its child node.
• Remove the child node from its original position.
3) Node to be deleted has two children:
• Get the inorder successor of that node.
• Replace the node with the inorder successor.
• Remove the inorder successor from its original position.
Node to be deleted has two children: Another Example
Note: Inorder successor is needed only when the right child is not empty.
In this particular case, the inorder successor can be obtained by finding the
minimum value in the right child of the node.
Driver code:
Driver code:
Output:
• Binary Search Tree Applications
• In multilevel indexing in the database
• For dynamic sorting
• For managing virtual memory areas in Unix kernel
Difference between
Difference between