34 lines
860 B
Python
34 lines
860 B
Python
# Time: O(N)
|
|
# Space: O(N)
|
|
|
|
# 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
|
|
from collections import deque
|
|
|
|
class BSTIterator:
|
|
items = None
|
|
|
|
def __init__(self, root: Optional[TreeNode]):
|
|
def inorder(node):
|
|
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
|
|
|
|
# In-order traversal of a BST gives us values in
|
|
# sorted order
|
|
self.items = deque(inorder(root))
|
|
|
|
def next(self) -> int:
|
|
return self.items.popleft()
|
|
|
|
def hasNext(self) -> bool:
|
|
return len(self.items) > 0
|
|
|
|
|
|
# Your BSTIterator object will be instantiated and called as such:
|
|
# obj = BSTIterator(root)
|
|
# param_1 = obj.next()
|
|
# param_2 = obj.hasNext()
|