23 · Binary Search Trees

#173 Binary Search Tree Iterator

Mediumsolve on LeetCode ↗

frequently reported atMetaLinkedInMicrosoftAmazonGoogleApple

the problem

In plain words

Implement BSTIterator over a BST's inorder sequence: next() returns the next smallest value, hasNext() tells whether one exists.

in [7,3,15,null,null,9,20]; next, next, hasNext, next, hasNext, next, hasNext, next, hasNext

out 3, 7, true, 9, true, 15, true, 20, false

  • 1 ≤ number of nodes ≤ 10⁵
  • 0 ≤ Node.val ≤ 10⁶
  • At most 10⁵ calls
  • Follow-up: average O(1) time and O(h) memory

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #230
    2. #94
    3. #285
      Inorder Successor in BST
      Mediumin BSTLeetCode Premium