Skip to main content
mediumBlind 75

Kth Smallest Element in a BST

Return the kth smallest value in the BST (1-indexed) Example: [3,1,4,null,2], k=1 => 1

Given the root of a non-empty binary search tree with integer node values and an integer k, return the kth smallest node value, counting from 1. If the tree has n nodes, k is guaranteed to satisfy 1 <= k <= n. For example, root = [3,1,4,null,2] and k = 2 return 2.

Examples

You write

kth_smallest(root: Optional[TreeNode], k: int)

  1. Example 1

    Input
    root = [3,1,4,null,2], k = 1
    returns
    1
  2. Example 2

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

The pattern behind it

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Kth Smallest Element in a BSTmedium