Recursive Inorder Traversal
Intuition
An inorder traversal of a BST visits nodes in ascending order. We can leverage this property to find the kth smallest element by performing an inorder traversal and counting nodes as we visit them. When our counter reaches k, the current node holds the answer. We can either collect all values into a sorted list and return the kth element, or use a counter to stop early once we reach the kth node.
Algorithm
- Perform an inorder traversal of the BST (left, node, right).
- Maintain a counter that increments each time a node is visited.
- When the counter equals k, record the current node's value as the result.
- Return the recorded result.
O(n) in the worst case, O(h + k) on averageSpaceO(h) where h is the height of the treeCode (C++ · Java · Python · Go)
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int count = 0;
int result = 0;
inorder(root, k, count, result);
return result;
}
private:
void inorder(TreeNode* node, int k, int& count, int& result) {
if (node == nullptr) return;
inorder(node->left, k, count, result);
count++;
if (count == k) {
result = node->val;
return;
}
inorder(node->right, k, count, result);
}
};class Solution {
private int count = 0;
private int result = 0;
public int kthSmallest(TreeNode root, int k) {
count = 0;
result = 0;
inorder(root, k);
return result;
}
private void inorder(TreeNode node, int k) {
if (node == null) return;
inorder(node.left, k);
count++;
if (count == k) {
result = node.val;
return;
}
inorder(node.right, k);
}
}def kthSmallest(root: Optional[TreeNode], k: int) -> int:
count = [0]
result = [0]
def inorder(node):
if not node:
return
inorder(node.left)
count[0] += 1
if count[0] == k:
result[0] = node.val
return
inorder(node.right)
inorder(root)
return result[0]func kthSmallest(root *TreeNode, k int) int {
count := 0
result := 0
var inorder func(*TreeNode)
inorder = func(node *TreeNode) {
if node == nil {
return
}
inorder(node.Left)
count++
if count == k {
result = node.Val
return
}
inorder(node.Right)
}
inorder(root)
return result
}