A python generator solution


  • 0
    C
    class BSTIterator(object):
        def __init__(self, root):
            """
            :type root: TreeNode
            """
            self.iterator = self.inorder(root)
            self.cur = 0
            self.used = True
    
        def hasNext(self):
            """
            :rtype: bool
            """
            if not self.used:
                return True
            try:
                self.cur = self.iterator.next()
                self.used = False
            except:
                return False
            return True
    
        def next(self):
            """
            :rtype: int
            """
            if not self.used:
                ret = self.cur
            else:
                ret = self.iterator.next()
            self.used = True
            return ret
    
        def inorder(self, root):
            if not root:
                return
            for node in self.inorder(root.left):
                yield node
            yield root.val
            for node in self.inorder(root.right):
                yield node
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.