Design an iterator for a binary search tree that performs an in-order traversal. The iterator is created from the root of the tree and has two operations:
-
next()
returns the next smallest number in the BST.
-
has_next()
returns whether there is a next number in the traversal.
Function Signature
class TreeNode:
def __init__(self, val: int = 0, left: "TreeNode | None" = None, right: "TreeNode | None" = None):
self.val = val
self.left = left
self.right = right
class BSTIterator:
def __init__(self, root: TreeNode | None) -> None: ...
def next(self) -> int: ...
def has_next(self) -> bool: ...
Rules
-
The tree is written as a level-order list with
None
for a missing child, as in the examples. The tree is built from that list and its root is passed to the constructor.
-
A test is a list of operations with their arguments. The output has one entry per operation:
None
for the constructor and the returned value for each
next()
or
has_next()
call.
-
next()
returns values in in-order sequence (left subtree, node, right subtree), which is ascending order for a BST.
-
next()
is only called when a next value exists.
has_next()
does not move the iterator.
Constraints
-
The number of nodes in the tree is in the range
[1, 10^5]
-
Node values are in the range
[0, 10^6]
-
At most
10^5
calls will be made to
has_next
and
next
Examples
Input: operations = ["BSTIterator", "next", "next", "has_next", "next", "has_next", "next", "has_next", "next", "has_next"], arguments = [[[7, 3, 15, None, None, 9, 20]], [], [], [], [], [], [], [], [], []]
Output: [None, 3, 7, True, 9, True, 15, True, 20, False]
The tree has root 7 with children 3 and 15, and 15 has children 9 and 20, so the in-order sequence is 3, 7, 9, 15, 20. The next() calls return those values in order, and has_next() turns False only after 20 has been returned.
Input: operations = ["BSTIterator", "has_next", "next", "has_next", "next", "has_next"], arguments = [[[5, 2, 8, 1, 4]], [], [], [], [], []]
Output: [None, True, 1, True, 2, True]
The tree has root 5 with children 2 and 8, and 2 has children 1 and 4, so the in-order sequence is 1, 2, 4, 5, 8. After two next() calls the values 4, 5 and 8 remain, so every has_next() returns True.