leetcode Binary Search Tree Iterator python

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

class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.stack = []
        self.pushLeft(root)

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.stack

    def next(self):
        """
        :rtype: int
        """
        top=self.stack.pop()
        self.pushLeft(top.right)
        return top.val
    def pushLeft(self,node):
        while node:
            self.stack.append(node)
            node=node.left

# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())

 

posted @ 2015-12-06 22:06  hao.ma  阅读(138)  评论(0编辑  收藏  举报