Introduction
Insert into BST means:
- adding new node
inside Binary Search Tree
while maintaining BST rules
BST Property:
Left subtree values < Root value < Right subtree values Goal:
- find correct position
- insert new value
- preserve BST ordering
Example:
Before Insert:4
/ \
2 7
/ \
1 3
Insert:
5
After Insert:
4
/ \
2 7
/ \ /
1 3 5
Explanation:
5 is smaller than 7 and greater than 4, so it becomesleft child of 7.This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5 Approach : Recursive BST Insertion
Explanations:
Explanation:
The idea is:
- compare current node
with insertion value - move to correct subtree
- insert at empty position
Steps:
- Visit current node.
- Compare insertion value.
- Move left if smaller.
- Move right if larger.
- Insert node at null position.
Conditions:
value < root.value → move left value > root.value → move right This approach:
- uses DFS recursion
- preserves BST ordering
Dry Run
Visit:4
5 > 4
Move right.
Visit:
7
5 < 7
Move left.
Left child is null.
Insert:
5
Practice :