Skip to content

Instantly share code, notes, and snippets.

@iamprayush
Last active September 20, 2020 12:37
Show Gist options
  • Save iamprayush/9eab8045a3514d064965dbd39587cfc2 to your computer and use it in GitHub Desktop.
Save iamprayush/9eab8045a3514d064965dbd39587cfc2 to your computer and use it in GitHub Desktop.
Binary Search Tree Iterator
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.curr_node = root
def next(self) -> int:
while self.curr_node:
self.stack.append(self.curr_node)
self.curr_node = self.curr_node.left
self.curr_node = self.stack.pop()
ans = self.curr_node.val
self.curr_node = self.curr_node.right
return ans
def hasNext(self) -> bool:
return len(self.stack) != 0 or self.curr_node is not None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment