Binary Search Tree Iterator
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,nullfor a missing child), thennext()andhasNext()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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more tree traversals problems
- 94Binary Tree Inorder TraversalEasysolve
- 144Binary Tree Preorder TraversalEasysolve
- 145Binary Tree Postorder TraversalEasysolve
- 530Minimum Absolute Difference in BSTEasysolve
- 98Validate Binary Search TreeMediumsolve
- 230Kth Smallest Element in a BSTMediumsolve
- 114Flatten Binary Tree to Linked ListMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.