Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    The k-th smallest value in a search tree

    MediumAbout 25 minFull AccessLearn it: Binary Search Trees in C#: Validation, LCA, Kth Smallest and SortedSet

    The task

    A ranking service keeps scores in a binary search tree: for every node, all values in its left subtree are smaller and all values in its right subtree are larger, and no value repeats. It asks for the k-th smallest score many times, with small k.

    Complete KthSmallest(TreeNode root, int k). Return the k-th smallest value in the tree, where 1 ≤ k ≤ the number of nodes. Stop as soon as you know the answer: the tests call your method 100,000 times on a tree of 100,000 nodes. Do not change the tree. The TreeNode class is given; do not change it.

    Signature

    public static int KthSmallest(TreeNode root, int k)

    Examples

    • tree [5, 3, 7, 2, 4, 6, 8], k = 4 → 5. In ascending order the values are 2, 3, 4, 5, ...
    • tree [10, 5, 15, null, 7], k = 3 → 10. 5, 7, then 10; 7 is the right child of 5.

    Limits: Up to 100,000 nodes. Trees are written level by level, with null for a missing child.

    The tests check: one node, the smallest, middle and largest values, chains to the left and to the right, negative values, and 100,000 calls with small k on a 100,000-node tree in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      // A node of a binary tree. Do not change this class: the tests build trees with it.
      public sealed class TreeNode
      {
          public int Val;
          public TreeNode? Left;
          public TreeNode? Right;
      
          public TreeNode(int val, TreeNode? left = null, TreeNode? right = null)
          {
              Val = val;
              Left = left;
              Right = right;
          }
      }
      
      public static class Solution
      {
          // Returns the k-th smallest value of a binary search tree (k = 1 is the smallest).
          public static int KthSmallest(TreeNode root, int k)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.