Skip to content

How to Fix Kth Smallest Element in BST Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Kth Smallest Element in BST Errors. We cover key concepts, practical examples, and best practices.

Fix kth smallest element in bst errors when inorder doesn't early-terminate or k tracking fails across calls.

Quick Fix

Wrong

def kth(r,k):
    vals=[]
    def dfs(n):
        if not n or len(vals)>=k: return
        dfs(n.left); vals.append(n.val); dfs(n.right)
    dfs(r)
    return vals[-1]

O(n) space for vals. Can't early-exit cleanly.

def kth(r,k):
    st=[]; cur=r
    while st or cur:
        while cur: st.append(cur); cur=cur.left
        cur=st.pop(); k-=1
        if k==0: return cur.val
        cur=cur.right
    return -1
BST [3,1,4,null,2], k=1 -> 1. k=3 -> 3. O(k+log n).

Prevention

Iterative inorder. Decrement k on each visited node. Stop when k=0.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is kth smallest?

Find kth (1-indexed) in BST. Inorder visits in sorted order.

Why iterative?

Can pause/resume. Recursive needs all values or mutable counter.

Kth largest?

Reverse inorder (right, root, left) or (n-k+1)th smallest.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro