LeetCode 230: Kth Smallest Element In A Bst — Step-by-Step Visual Trace

Published: (April 9, 2026 at 02:37 AM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Problem Description

Find the kth smallest element in a Binary Search Tree (BST), where k is 1‑indexed. The function should return the value of the kth smallest node when all nodes are sorted in ascending order.

Approach

The solution uses inorder traversal of the BST, which naturally visits nodes in sorted ascending order. It recursively traverses the left subtree, processes the current node, then traverses the right subtree, building a complete sorted list of all values before returning the kth element.

Complexity

  • Time:O(n)
  • Space:O(n)

Code

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        def inorder_traversal(node):
            if not node:
                return []

            left = inorder_traversal(node.left)
            right = inorder_traversal(node.right)

            return left + [node.val] + right

        inorder_values = inorder_traversal(root)
        return inorder_values[k - 1]

Interactive Visualization

Open TraceLit — the visual algorithm tracer for LeetCode practice.

0 views
Back to Blog

Related posts

Read more »