"""
QUESTION:
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.
ANSWER:
using stack
"""

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class BSTIterator:
    # @param root, a binary search tree's root node
    def __init__(self, root):
        self.st = []

    # @return a boolean, whether we have a next smallest number
    def hasNext(self):
        return self.st != None

    # @return an integer, the next smallest number
    def next(self):
        top = self.st.pop()
        self.pushleft(top.right)
        return top.val

    def pushleft(self,node):
        while node:
            self.st.append(node)
            node = node.left

if __name__ == '__main__':
    print