Kth Smallest Element in BST in DSA Python - Time & Space Complexity
We want to understand how long it takes to find the kth smallest value in a Binary Search Tree (BST).
Specifically, how the time grows as the tree size and k change.
Analyze the time complexity of the following code snippet.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kth_smallest(root, k):
stack = []
while True:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right
This code finds the kth smallest element by doing an in-order traversal using a stack.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing nodes in the BST in order using a stack.
- How many times: Up to k nodes are visited and processed.
As k grows, the number of nodes visited grows roughly linearly with k, not the total number of nodes n.
| Input Size (n) | Approx. Operations (visiting nodes) |
|---|---|
| 10, k=3 | About 3 nodes |
| 100, k=50 | About 50 nodes |
| 1000, k=1000 | About 1000 nodes (whole tree) |
Pattern observation: The work grows linearly with k, not necessarily with n.
Time Complexity: O(h + k)
This means the time depends on the tree height h plus the number k of nodes we visit to find the kth smallest.
[X] Wrong: "The time is always O(n) because we might visit all nodes."
[OK] Correct: We stop as soon as we find the kth smallest, so if k is small, we visit fewer nodes than n.
Understanding this complexity helps you explain how efficient your solution is when working with trees and partial traversals.
"What if the BST is balanced vs very skewed? How would the time complexity change?"
Practice
Kth Smallest Element in BST mean?Solution
Step 1: Understand BST ordering
A Binary Search Tree (BST) stores elements so that left child is smaller and right child is larger.Step 2: Define Kth smallest element
The Kth smallest element is the element that appears in the Kth position when all elements are sorted ascending.Final Answer:
The element that is the Kth in ascending order in the BST -> Option BQuick Check:
Kth smallest means sorted order position [OK]
- Confusing Kth smallest with Kth largest
- Thinking it means the root node
- Assuming K is the value, not position
Solution
Step 1: Check parameter order and types
The function should take the root node and an integer k to find the Kth smallest element.Step 2: Validate correct typing and order
def kth_smallest(root: Optional[TreeNode], k: int) -> int: correctly uses root as TreeNode (or Optional) and k as int, returning int.Final Answer:
def kth_smallest(root: Optional[TreeNode], k: int) -> int: -> Option AQuick Check:
Correct parameter order and types [OK]
- Swapping parameter order
- Using wrong type for k (like string)
- Missing k parameter
k = 3, what is the output of the function kth_smallest(root, 3)?
5
/ \
3 7
/ \ \
2 4 8
Solution
Step 1: List BST elements in ascending order
Inorder traversal gives: 2, 3, 4, 5, 7, 8.Step 2: Identify the 3rd smallest element
The 3rd element in this list is 4.Final Answer:
4 -> Option AQuick Check:
Inorder 3rd element = 4 [OK]
- Choosing root or random node instead of Kth
- Counting nodes incorrectly
- Confusing Kth smallest with Kth largest
def kth_smallest(root, k):
stack = []
while True:
while root:
stack.append(root)
root = root.right # Bug here
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.left
Solution
Step 1: Analyze traversal direction
For Kth smallest, we do inorder traversal: left -> node -> right. The code wrongly goes right first.Step 2: Identify correct child to traverse first
It should go to the left child first to get smallest elements first.Final Answer:
It should go to the left child first, not right -> Option DQuick Check:
Inorder traversal starts with left child [OK]
- Going right child first in inorder
- Not using stack properly
- Incorrect decrement of k
Solution
Step 1: Understand traversal types
Inorder traversal visits nodes in ascending order in BST.Step 2: Apply inorder traversal to find Kth smallest
Perform inorder traversal and stop at the 5th node visited to get the 5th smallest element.Final Answer:
Perform inorder traversal and return the 5th visited node -> Option CQuick Check:
Inorder traversal gives sorted order [OK]
- Using preorder or postorder which are not sorted
- Ignoring left subtree nodes
- Assuming root is always Kth smallest
Ready to prove it?
Pass the test and this pattern moves unknown
