Kth Smallest Element in a BST
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.
Constraints:
- The number of nodes in the tree is n.
- 1 <= k <= n <= 10^4
- 0 <= Node.val <= 10^4
Input Format:
- The root of a binary search tree
- An integer k
Output Format:
- Return the kth smallest element in the BST
Examples:
Example 1:
Input:
root = [3,1,4,null,2], k = 1
Output:
1
Explanation:
The tree is: 3 / \ 1 4 \ 2 The 1st smallest element is 1.
Example 2:
Input:
root = [5,3,6,2,4,null,null,1], k = 3
Output:
3
Explanation:
The tree is: 5 / \ 3 6 / \ 2 4 / 1 The 3rd smallest element is 3.
Solutions
Recursive In-Order Traversal
Use recursive in-order traversal to visit nodes in ascending order. The kth node visited will be the kth smallest element.
Iterative In-Order Traversal
Use an iterative approach with a stack to perform in-order traversal. Stop when the kth element is found to avoid unnecessary traversal.
Follow-Up: Optimized Solution with BST Property
An optimized solution that maintains a count of nodes in the left subtree to avoid unnecessary traversals. This is useful when the tree structure doesn't change but the function is called multiple times.
Algorithm Walkthrough
Example input: nums = []
Step-by-step execution:
- Start in-order traversal at root node 3
- Recursively traverse to the left: node 1
- Node 1 has no left child, so process node 1 and add to result: [1]
- Move to the right child of node 1: node 2
- Node 2 has no left child, so process node 2 and add to result: [1, 2]
- Return to node 3 and process it: [1, 2, 3]
- Move to the right child of node 3: node 4
- Node 4 has no left child, so process node 4 and add to result: [1, 2, 3, 4]
- Complete in-order traversal result: [1, 2, 3, 4]
- Return the kth (1st) element: 1
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the in-order traversal of a BST to find the kth smallest element.
Key visualization elements:
- current node
- visited nodes
- stack state
- kth element found
Implementation Notes
This problem tests understanding of Binary Search Tree properties and tree traversal algorithms. The key insight is that an in-order traversal of a BST visits nodes in ascending order.