Binary Search Tree-(BST) Operations
A Binary Search Tree (BST) is a binary tree in which each node has the following property:
-
The left subtree of a node contains only nodes with keys less than the node’s key.
-
The right subtree of a node contains only nodes with keys greater than the node’s key.
-
Both left and right subtrees must also be BSTs.
Properties of a Binary Search Tree
✅ Common BST Operations
-
Creation of BST Node
-
Allocate memory for a new node.
-
Initialize
data,left, andright.
-
-
Insertion
-
Compare the new key with the root.
-
If smaller, go left; if larger, go right.
-
Repeat recursively until the correct position is found.
-
-
Searching
-
Start at root.
-
If key < root, search in left subtree.
-
If key > root, search in right subtree.
-
If equal, node is found.
-
-
Traversal
-
Inorder (L, Root, R): Gives sorted order.
-
Preorder (Root, L, R).
-
Postorder (L, R, Root).
-
-
Finding Minimum and Maximum
-
Minimum → Keep moving left until
NULL. -
Maximum → Keep moving right until
NULL.
-
-
Deletion
-
Case 1: Node is a leaf → Delete directly.
-
Case 2: Node has one child → Replace node with its child.
-
Case 3: Node has two children → Replace with inorder successor (or predecessor), then delete successor.
-
Algorithms and Pseudo code : Operations on a Binary Search Tree
Definition and Creation
Insertion
- To insert a new value into the tree, compare it to the current node's value.
- If the value is less than the current node, go to the left subtree; if greater, go to the right subtree.
- Repeat this process until an empty spot is found, then insert the new value as a leaf.
- If the tree is empty is null, create a new node with the given key and return it.
- else Compare the key with the current node's key.
- If the key is less than the current node's key, recursively insert into the left subtree.
- If the key is greater than the current node's key, recursively insert into the right subtree.
- return the modified node.
Search
- If the root is null or the key is equal to the root's key, return the root (key found).
- If the key is smaller than the root's key, recursively search in the left subtree.
- If the key is greater than the root's key, recursively search in the right subtree.
Traversal
void inorder(struct node* root)
(c) Postorder Traversal
Minimum and Maximum
- Find the minimum value by traversing the left subtree until a leaf is reached.
- Find the maximum value by traversing the right subtree until a leaf is reached.
Deletion
To delete a node with a specific value:- If the node is a leaf or has only one child, remove the node and replace it with its child.
- If the node has two children, find the node's in-order successor (the smallest node in its right subtree), replace the node's value with the successor's value, and then delete the successor.






Comments
Post a Comment