sophryu99 / algorithm

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

173. Binary Search Tree Iterator #6

Open sophryu99 opened 1 year ago

sophryu99 commented 1 year ago

Approach

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

  1. In-order traversal: Left -> Root -> Right
  2. Initialize an empty stack, push the Left node of the root and continue until it reaches the last node.
  3. hasNext(): checks if there is more to traverse to the right of the pointer.
  4. next(): get the top most node from the stack, move the pointer to the right, and return the value at the pointer.
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

# In order traversal: Left -> Root -> Right
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

    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

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

n: number of nodes Time Complexity: O(n) Memory: O(n)