15. Kth Smallest Element in BST
β GFG solution to the Kth Smallest Element in BST problem: find the kth smallest element in a binary search tree using iterative inorder traversal with stack. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given the root of a Binary Search Tree (BST) and an integer k
, the task is to find the kth smallest element in the BST. If there is no kth smallest element present, return -1
.
A BST is a tree where for each node, all elements in the left subtree are smaller and all elements in the right subtree are greater. An inorder traversal of a BST yields elements in sorted (ascending) order.
π Examples
Example 1
Input: root = [20, 8, 22, 4, 12, N, N, N, N, 10, 14], k = 3
Output: 10
Explanation: The inorder traversal of the BST is [4, 8, 10, 12, 14, 20, 22].
The 3rd smallest element is 10.
Example 2
Input: root = [2, 1, 3], k = 5
Output: -1
Explanation: There is no 5th smallest element in the BST as the size of BST is 3.
π Constraints
$1 \le \text{number of nodes, k} \le 10^4$
$1 \le \text{node->data} \le 10^4$
β
My Approach
The optimal approach uses Iterative Inorder Traversal with an explicit stack to efficiently find the kth smallest element:
Iterative Stack-Based Inorder Traversal
Initialize Variables:
Use an explicit stack to simulate the recursion call stack.
Maintain a counter
c
initialized to 0 to track visited nodes.Use pointer
n
to traverse the tree starting from root.
Traverse to Leftmost Node:
Push all left children onto the stack while moving to the leftmost node.
This ensures we visit nodes in ascending order.
Process Current Node:
Pop a node from the stack.
Increment the counter
c
.If
c
equalsk
, we've found the kth smallest elementβreturn its value.
Move to Right Subtree:
Move to the right child of the current node.
Repeat the process for the right subtree.
Early Termination:
The algorithm stops as soon as the kth element is found.
No need to traverse the entire tree, making it efficient for small values of k.
Return Result:
If k exceeds the number of nodes, return
-1
.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(k), as we only traverse k nodes in the worst case. For a balanced BST with height h, we visit at most h nodes to reach the leftmost node, then k-1 more nodes to find the kth smallest element. In the best case (when k is small), we stop early without traversing the entire tree.
Expected Auxiliary Space Complexity: O(h), where h is the height of the BST. The stack stores at most h nodes (the height of the tree) at any point during traversal. For a balanced BST, h = O(log n), and for a skewed BST, h = O(n).
βοΈ Code (C)
int kthSmallest(struct Node* root, int k) {
int s[100000], t = 0, c = 0;
struct Node* n = root;
while (n || t) {
while (n) s[t++] = (long)n, n = n->left;
n = (struct Node*)s[--t];
if (++c == k) return n->data;
n = n->right;
}
return -1;
}
π§βπ» Code (C++)
class Solution {
public:
int kthSmallest(Node *root, int k) {
stack<Node*> s;
Node* n = root;
int c = 0;
while (n || !s.empty()) {
while (n) {
s.push(n);
n = n->left;
}
n = s.top(); s.pop();
if (++c == k) return n->data;
n = n->right;
}
return -1;
}
};
β Code (Java)
class Solution {
public int kthSmallest(Node root, int k) {
Stack<Node> s = new Stack<>();
Node n = root;
int c = 0;
while (n != null || !s.isEmpty()) {
while (n != null) {
s.push(n);
n = n.left;
}
n = s.pop();
if (++c == k) return n.data;
n = n.right;
}
return -1;
}
}
π Code (Python)
class Solution:
def kthSmallest(self, root, k):
s, n, c = [], root, 0
while n or s:
while n:
s.append(n)
n = n.left
n = s.pop()
c += 1
if c == k: return n.data
n = n.right
return -1
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated