 # Binary Search Tree Iterator

#1

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling `next()` will return the next smallest number in the BST.

Note: `next()` and `hasNext()` should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

#2

The algorithms below uses a Stack to replicate an inorder traversal that gives an ordered list of elements in a binary search tree.

``````/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/

type Stack []*TreeNode

func (s *Stack) Push(n *TreeNode) {
*s = append(*s, n)
}

func (s *Stack) Pop() (n *TreeNode) {
if s.Len()!=0{
x := s.Len() - 1
n = (*s)[x]
*s = (*s)[:x]
return n
}

return nil
}

func (s *Stack) Len() int {
return len(*s)
}

type BSTIterator struct {
stack Stack
}

func Constructor(root *TreeNode) BSTIterator {
s := Stack{}
b := BSTIterator{stack : s}
b.pushAll(root)
return b
}

/** @return the next smallest number */
func (this *BSTIterator) Next() int {
node := this.stack.Pop()
this.pushAll(node.Right)
return node.Val
}

func (this *BSTIterator) pushAll(node *TreeNode){
for node!= nil{
this.stack.Push(node)
node = node.Left
}
}

/** @return whether we have a next smallest number */
func (this *BSTIterator) HasNext() bool {
return this.stack.Len()!=0
}

/**
* Your BSTIterator object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Next();
* param_2 := obj.HasNext();
*/
``````

#3

Similar code that use a Stack, but in Java.

``````public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
this.stack = new Stack<>();
pushAll(root);
}

private void pushAll(TreeNode node){
while(node!=null){
stack.push(node);
node = node.left;
}
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}

/** @return the next smallest number */
public int next() {
TreeNode cur = stack.pop();
pushAll(cur.right);
return cur.val;
}
}
``````