sophryu99 / algorithm

algorithm in python - 4 questions a week
4 stars 1 forks source link

173. Binary Search Tree Iterator #34

Open sophryu99 opened 1 year ago

sophryu99 commented 1 year ago

https://leetcode.com/problems/binary-search-tree-iterator/

Approach

class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        self.stack = []
        self.pushLeft(root)

    def pushLeft(self, root):
        while root:
            self.stack.append(root)
            root = root.left

    # Moves the pointer to the right
    def next(self) -> int:
        node = self.stack.pop()
        # Move the pointer to right
        self.pushLeft(node.right)
        return node.val

    def hasNext(self) -> bool:
        return len(self.stack) > 0