Last active
September 20, 2020 12:37
-
-
Save iamprayush/9eab8045a3514d064965dbd39587cfc2 to your computer and use it in GitHub Desktop.
Binary Search Tree Iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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