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 the BSTIterator class. The root of 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() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.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 may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
hasNext, and next. Follow up:
next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?The basic intuition is to leverage the property of a BST where an in-order traversal gives nodes in a non-decreasing order. We can perform an in-order traversal of the tree, store all nodes in a list, and then use this list to ensure constant time access to the next smallest node.
next() simply retrieves the element at the current index and then increments it.hasNext() checks if the current index is less than the list size.Constructor: O(N), where N is the number of nodes in the tree, due to the in-order traversal.next(): O(1).hasNext(): O(1).The goal is to simulate the in-order traversal using controlled stack-based recursion. The benefit is an iterative approach with a controlled stack of nodes which represents the path from the root to the next smallest node. Thus, it uses less memory than storing all nodes.
hasNext() is simple: check if there are any nodes left in the stack.next(), pop the top node from the stack (the current smallest).Constructor: O(H), where H is the height of the tree, due to pushing nodes from the root to the leftmost leaf.next(): Amortized O(1), each node pushed or popped exactly once.hasNext(): O(1).