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

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit