Introduction
Kth Smallest Element means:
- finding kth smallest value inside Binary Search Tree efficiently
BST Property:
Inorder traversal of BST gives sorted order.Goal:
- return kth smallest node without sorting array separately
Example:
5/ \
3 6
/ \
2 4
/
1
k = 3
Output:
3
Explanation:
Inorder traversal: [1,2,3,4,5,6]
3rd smallest element:3
This problem is one of the most important applications of:
Inorder DFS Traversal Constraints
1 <= Number of Nodes <= 10^5Approach : Inorder DFS Traversal
Explanations:
Explanation:
The idea is:
- inorder traversal of BST
produces sorted sequence - count visited nodes
during traversal
Traversal Order:
Left → Root → RightSteps:
- Traverse left subtree.
- Visit current node.
- Increment counter.
- Check kth position.
- Traverse right subtree.
- Return kth value.
Conditions:
count == k → kth smallest foundThis approach:
- avoids extra sorting
- efficiently uses BST ordering
Dry Run
Tree:5
/ \
3 6
/ \
2 4
/
1
Inorder:
1 → 2 → 3 → 4 → 5 → 6
k = 3
3rd visited node:
3
Answer:
3