LeetCode 230: Kth Smallest Element in a BST
Problem Description
Explanation
To find the kth smallest element in a BST, we can perform an in-order traversal of the BST which will give us the elements in sorted order. While doing the in-order traversal, we keep track of the count of elements visited so far. When the count reaches k, we return the current node's value.
- Initialize a variable
count
to keep track of the number of elements visited so far. - Perform an in-order traversal of the BST.
- When visiting a node, increment the
count
. - If
count
becomes equal tok
, return the value of the current node. - If not, continue the traversal until the end.
- The kth smallest element will be the value returned when
count
equalsk
.
Time complexity: O(n) where n is the number of nodes in the BST. Space complexity: O(h) where h is the height of the BST.
Solutions
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
int count = 0;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
count++;
if (count == k) {
return current.val;
}
current = current.right;
}
return -1;
}
}
Related LeetCode Problems
Loading editor...