My solution modified from Inorder Traversal


  • 0
    J
    class BSTIterator(object):
        def __init__(self, root):
            """
            :type root: TreeNode
            """
            self.nums = []
            self.stack = []
    
            self.stack.append((root, False))
            while self.stack:
                node, flag = self.stack.pop()
                if node:
                    if flag:
                        self.nums.append(node.val)
                    else:
                        self.stack.append((node.right, False))
                        self.stack.append((node, True))
                        self.stack.append((node.left, False))
    
        def hasNext(self):
            """
            :rtype: bool
            """
            if len(self.nums)>0:
                return True
            else: 
                return False
    
        def next(self):
            """
            :rtype: int
            """
            return self.nums.pop(0)
    

Log in to reply
 

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