MEDIUM NC#57 Blind #69 Trees
230. Kth Smallest Element in a BST
๐ Problem
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) in all the BST. It is guaranteed that there will always be a valid answer.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขMidpoint overflow-safe math
- โขLoop invariants
- โขMonotonic condition design
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Binary Search reasoning pattern
๐ก Approach
- โ Use iterative inorder traversal with stack
- โ Kth smallest element is the kth element in inorder traversal
- โ Keep track of count while traversing
- โ When count reaches k, we've found our answer
- โ Time: O(h + k), Space: O(h) where h is tree height
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse iterative inorder traversal with stack
- โขKth smallest element is the kth element in inorder traversal
- โขKeep track of count while traversing
Common Pitfalls
- โขWhen count reaches k, we've found our answer
- โขTime: O(h + k), Space: O(h) where h is tree height
๐งช Test Cases
Test Case 1
Not run Input:
_kthSmallest(_bst1, 1); Expected:
1 Test Case 2
Not run Input:
_kthSmallest(_bst2, 3); Expected:
4 Test Case 3
Not run Input:
_kthSmallest(root: TreeNode | null, k: number); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output