DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

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

Medium — Binary Search Tree | Tree Traversal | Recursion | Inorder Traversal

The Problem

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

This 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.

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]
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)