Skip to content

Latest commit

 

History

History
54 lines (45 loc) · 1.12 KB

173.md

File metadata and controls

54 lines (45 loc) · 1.12 KB

173. Binary Search Tree Iterator

Solution 1

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

    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.root = root
        self.p = root
        self.stack = []


    def next(self):
        """
        :rtype: int
        """
        ans = -1
        while self.p or self.stack:
            if self.p:
                self.stack.append(self.p)
                self.p = self.p.left
            else:
                self.p = self.stack.pop()
                ans = self.p.val
                self.p = self.p.right
                break
        return ans


    def hasNext(self):
        """
        :rtype: bool
        """
        if self.p or self.stack:
            return True
        else:
            return False


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()