LeetCode-in-All

230. Kth Smallest Element in a BST

Medium

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 1:

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

Output: 1

Example 2:

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

Output: 3

Constraints:

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Solution

# Definition for a binary tree node.
#
# defmodule TreeNode do
#   @type t :: %__MODULE__{
#           val: integer,
#           left: TreeNode.t() | nil,
#           right: TreeNode.t() | nil
#         }
#   defstruct val: 0, left: nil, right: nil
# end

defmodule Solution do
  @spec kth_smallest(root :: TreeNode.t() | nil, k :: integer) :: integer
  def kth_smallest(root, k) do
    {_, value} = find_kth_smallest(root, k, 0)
    value
  end

  defp find_kth_smallest(nil, _, count), do: {count, nil}

  defp find_kth_smallest(node, k, count) do
    # Search left subtree
    {count, left_value} = find_kth_smallest(node.left, k, count)
    
    # Check if we have found the k-th smallest element
    if left_value do
      {count, left_value}
    else
      count = count + 1
      
      if count == k do
        {count, node.val}
      else
        # Search right subtree
        find_kth_smallest(node.right, k, count)
      end
    end
  end
end