Python Solution using In-Order Traversal


  • 0
    class BSTIterator(object):
    def __init__(self, root):
        self.stack, self.p = [(1, root)], None
    
    def hasNext(self):
        while self.stack:
            self.p = self.stack.pop()
            if not self.p[1]: continue
            if self.p[0] == 0:
                return True
            else:
                self.stack.extend([(1, self.p[1].right), (0, self.p[1]), (1, self.p[1].left)])
        return False
    
    def next(self):
        return self.p[1].val

Log in to reply
 

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