Post

Leetcode 230. Kth Smallest Element in a BST

Explanation for Leetcode 230 - Kth Smallest Element in a BST, and its solution in Python.

Problem

Leetcode 230 - Kth Smallest Element in a BST

Example: Desktop View

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

Desktop View

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

Approach

We can use In-order traversal then return k-1’th that we interact with.

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        res = []
        def dfs(root):
            if not root:
                return
            
            dfs(root.left)
            res.append(root.val)
            dfs(root.right)
        
        return res[k-1]
    

Time Complexity and Space Complexity

Time Complexity: $O(n)$

Space Complexity: $O(n)$

This post is licensed under CC BY 4.0 by the author.