Introduction
Kth Smallest Element means:
- finding element
at kth position
inside sorted BST order
Important BST Property:
Inorder Traversal of BST gives sorted order Goal:
- traverse BST
in sorted sequence - stop at kth node
Example:
5/ \
3 6
/ \
2 4
/
1
k = 3
Sorted Order:
1 2 3 4 5 6
Answer:
3
Explanation:
Third smallest element in sorted BST order is 3.This problem is one of the most important applications of:
Inorder DFS TraversalConstraints
1 <= Number of Nodes <= 10^5 Approach : Inorder DFS Traversal
Explanations:
Explanation:
The idea is:
- inorder traversal
visits BST nodes
in ascending order
Traversal Order:
Left
→ Root→ Right
Steps:
- Traverse left subtree.
- Visit current node.
- Increase counter.
- Stop at kth node.
- Traverse right subtree.
This approach:
- uses DFS recursion
- leverages BST ordering
- avoids extra sorting
Dry Run
Visit:
1
Count:
1
Visit:
2
Count:
2
Visit:
3
Count:
3
Kth smallest found:3
Practice :