Kth Smallest Element in a BST — LeetCode 230 Python Solution

MediumTreeDepth-First SearchBinary Search TreeBinary Tree
Problem
#230
Reading time
3 min

The problem

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example

Input
root = [3,1,4,null,2], k = 1
Output
1

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stk = []
        while root or stk:
            if root:
                stk.append(root)
                root = root.left
            else:
                root = stk.pop()
                k -= 1
                if k == 0:
                    return root.val
                root = root.right

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 230. Kth Smallest Element in a BST is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 230. Kth Smallest Element in a BST?
LeetCode 230. Kth Smallest Element in a BST is rated Medium on LeetCode.
What is the time complexity of LeetCode 230. Kth Smallest Element in a BST?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 230. Kth Smallest Element in a BST?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 230. Kth Smallest Element in a BST cover?
LeetCode 230. Kth Smallest Element in a BST is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview