Binary Search Tree Iterator
Implement an iterator over a BST with O(h) memory and O(1) amortized next() operations.
01The problem
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of theBSTIteratorclass. Therootof the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You must implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree.
text
7
/ 3 15
/ 9 20
BSTIterator it = new BSTIterator(root);
it.next(); // 3
it.next(); // 7
it.hasNext(); // true
it.next(); // 9
it.hasNext(); // true
it.next(); // 15
it.hasNext(); // true
it.next(); // 20
it.hasNext(); // falseConstraints
- The number of nodes in the tree is in the range
[1, 10^5]. 0 <= Node.val <= 10^6- At most
10^5calls will be made tohasNext, andnext.
Loading the rest of the lesson…