Solving Kth Smallest Element in a BST: Navigating Tree Order
The "Kth Smallest Element in a BST" problem requires finding the kth smallest element in a Binary Search Tree (BST). This problem can be effectively tackled by understanding and utilizing the properties of BSTs, particularly inorder traversal.
Problem Statement
Given the root of a binary search tree and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example
Consider a binary search tree:
Example 1:

Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Solution Approach - Inorder Traversal
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function kthSmallest(root: TreeNode | null, k: number): number {
const stack: TreeNode[] = [];
let current = root;
let count = 0;
while (current || stack.length > 0) {
while (current) {
stack.push(current);
current = current.left;
}
let poppedValue = stack.pop();
if (poppedValue !== undefined) {
current = poppedValue;
count++;
if (count === k) return current.val;
current = current.right;
} else {
current = null; // or however you want to handle the undefined case
}
}
return -1;
}
Breaking Down the Solution
- Map for Inorder Indices: Create a map to quickly find the index of each value in the inorder sequence.
- Recursive Construction: Recursively build the left and right subtrees using the indices in the map to find the dividing point.
- Preorder Traversal: The preorder array guides the creation of each node, starting from the root.
Conclusion
Constructing a binary tree from preorder and inorder traversals is an intriguing challenge that tests understanding of tree properties and traversal techniques.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.