Binary Search Tree Iterator

Medium#173in-order

Design an iterator over a binary search tree. It is built from the root; next() returns the next value in increasing order, and hasNext() says whether any value is left. Both should take O(1) time on average and O(h) memory, where h is the height of the tree. Our tree: 12 with children 5 and 17; 5 has a right child, 9; 17 has a left child, 14. Our calls: BSTIterator(root), next(), next(), next(), hasNext(), next(), next(), hasNext() — they return 5, 9, 12, true, 14, 17, false.

input
Calls one after another: BSTIterator(root) gets the root of a binary search tree, written as on LeetCode (its values level by level, null for a missing child), then next() and hasNext() in any order.
returns
next() returns the tree's next value in increasing order (inorder), hasNext() whether there is one. LeetCode wants O(1) on average per call and O(h) memory.
constraints
  • 1 ≤ the number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 10⁶
  • root is a binary search tree
  • next() is called only while there is a next value
  • 2 ≤ calls ≤ 3000
our 9 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 */
var BSTIterator = function(root) {

};

/**
 * @return {number}
 */
BSTIterator.prototype.next = function() {

};

/**
 * @return {boolean}
 */
BSTIterator.prototype.hasNext = function() {

};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * var obj = new BSTIterator(root)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */
Ctrl ↵
format
reset

saved in this browser

9 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more tree traversals problems

Pattern “Tree traversals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.