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

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

via Dev.totracelit

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 ] Watch It Run TraceLit — See exactly where your code breaks

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles