Initialize an empty stack, push the Left node of the root and continue until it reaches the last node.
hasNext(): checks if there is more to traverse to the right of the pointer.
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)
Approach
https://leetcode.com/problems/binary-search-tree-iterator/description/
Left -> Root -> Right
n: number of nodes Time Complexity:
O(n)
Memory:O(n)