Binary Search Tree
Binary Search Tree
Theory
Why do we use BST (Binary Search Tree) for storing data? Well, BST allows for faster searching and sorting, insertion and deletion of data. This can happen because of the fundemental rules of Binary Search Trees, which are:
- For every node in a BST, the left subtree of the node must contain elements which are smaller than the element stored in the node.
- For every node in a BST. the right subtree of the node must contain elements which are greater than the element stored in the node
Therefore, traversing through a binary search will just be a matter of asking the question of greater or smaller.
Basic BST Operations
Search
This search algorithm will return a struct Node* datatype, this is just something that we need to keep in mind when applying this algorithm in our main function
Insert
Delete
This deletion operation requires some sort of visualisation to fully understand, especially on line 28. However, it is far more important for us to remember the 3 cases of the deletion algorithm which are:
- Node to be deleted is a leaf (no child)
- Just delete the node
- Node to be deleted has one child
- Replace the node to be deleted with the child node
- Node to be deleted has 2 child -
- In this case we need to search for the smallest element of the right subtree to substitute the position of the deleted node.
- We can also actually search for the greatest element of the left subtree.
Case 2 Visualisation:
Case 3 Visualisation:
I hope through these visualisations you can understand what the function minValuenode() does and also its importance. If we immediately replace the deleted with node with one of the child nodes, there is a chance that we break the fundemental rules of the a BST. So instead of doing that, we need to find the smallest element of the right child node (or the greatest in the left child node) to replace it with the deleted node.



Comments
Post a Comment