Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogleFacebookBloomberg

Kth Smallest Element in a BST

Choose your preparation mode3 modes available
Steps
setup

Initialize stack and current pointer

We start with an empty stack and set current to the root node (value 3). The count of visited nodes is zero.

💡 Initialization sets up the data structures needed for iterative in-order traversal.
Line:stack = [] current = root count = 0
💡 The traversal will begin from the root, and the stack will help us backtrack after reaching leftmost nodes.
📊
Kth Smallest Element in a BST - Watch the Algorithm Execute, Step by Step
Watching each stack operation and pointer movement reveals how in-order traversal naturally visits nodes in ascending order, making it the fastest way to understand the kth smallest element search.
Step 1/10
·Active fillAnswer cell
Current node: 1
3124
Current node: 2
3124
3124
Current node: 2
3124
Result: [1]
Current node: 2
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
Current node: 5
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
3124
Result: [1, 2, 3, 4]
Return: 1

Key Takeaways

In-order traversal visits BST nodes in ascending order, enabling direct access to the kth smallest element by counting visits.

This insight is hard to see from code alone because the traversal order and counting are implicit; visualization makes it explicit.

The stack stores nodes whose left subtrees are fully explored but whose right subtrees are yet to be visited, enabling backtracking.

Understanding the stack's role clarifies how iterative traversal mimics recursion.

The algorithm stops immediately when the kth smallest node is visited, optimizing performance by avoiding unnecessary traversal.

This early stopping is subtle in code but critical for efficiency, and visualization highlights this decision clearly.