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.
The number of nodes in the tree is in the range [1, 105].
0 <= Node.val <= 106
At most 105 calls will be made to hasNext, and next.
Follow up:
Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
Solutions
Solution 1
Thinking
Inorder on a BST is sorted. Up to \(10^5\) nodes and as many calls. A full inorder into an array makes \(\textit{next}/\textit{hasNext}\) a cursor move — amortized \(O(1)\) — but \(O(n)\) space. The follow-up wants \(O(h)\) memory.
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassBSTIterator:def__init__(self,root:TreeNode):definorder(root):ifroot:inorder(root.left)self.vals.append(root.val)inorder(root.right)self.cur=0self.vals=[]inorder(root)defnext(self)->int:res=self.vals[self.cur]self.cur+=1returnresdefhasNext(self)->bool:returnself.cur<len(self.vals)# Your BSTIterator object will be instantiated and called as such:# obj = BSTIterator(root)# param_1 = obj.next()# param_2 = obj.hasNext()
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */typeBSTIteratorstruct{stack[]*TreeNode}funcConstructor(root*TreeNode)BSTIterator{varstack[]*TreeNodefor;root!=nil;root=root.Left{stack=append(stack,root)}returnBSTIterator{stack:stack,}}func(this*BSTIterator)Next()int{cur:=this.stack[len(this.stack)-1]this.stack=this.stack[:len(this.stack)-1]fornode:=cur.Right;node!=nil;node=node.Left{this.stack=append(this.stack,node)}returncur.Val}func(this*BSTIterator)HasNext()bool{returnlen(this.stack)>0}/** * Your BSTIterator object will be instantiated and called as such: * obj := Constructor(root); * param_1 := obj.Next(); * param_2 := obj.HasNext(); */
/** * 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 */varBSTIterator=function(root){this.stack=[];for(;root!=null;root=root.left){this.stack.push(root);}};/** * @return {number} */BSTIterator.prototype.next=function(){letcur=this.stack.pop();letnode=cur.right;for(;node!=null;node=node.left){this.stack.push(node);}returncur.val;};/** * @return {boolean} */BSTIterator.prototype.hasNext=function(){returnthis.stack.length>0;};/** * 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() */
Solution 2
Thinking
Solution 1 flattens the whole tree. An explicit stack simulates inorder: push the left spine at init; \(\textit{next}\) pops, then pushes the left spine of the right child. At most \(h\) nodes sit on the stack, and each node is pushed and popped once.
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassBSTIterator:def__init__(self,root:TreeNode):self.stack=[]whileroot:self.stack.append(root)root=root.leftdefnext(self)->int:cur=self.stack.pop()node=cur.rightwhilenode:self.stack.append(node)node=node.leftreturncur.valdefhasNext(self)->bool:returnlen(self.stack)>0# Your BSTIterator object will be instantiated and called as such:# obj = BSTIterator(root)# param_1 = obj.next()# param_2 = obj.hasNext()