/173. Binary Search Tree Inorder Iterator

173. Binary Search Tree Inorder Iterator

Medium
Stack76.2% acceptance

Design a class InorderBSTIterator that iterates over the nodes of a binary search tree (BST) in in-order traversal. The iterator must support the following operations: (1) InorderBSTIterator(TreeNode root): initialize the iterator with the root node of the BST. (2) has_next(): return True if there is a next node in the in-order traversal, otherwise False. (3) get_next(): return the next node value in the in-order traversal. The first call to get_next() returns the smallest value in the BST. You may assume get_next() is only called when has_next() is True. The TreeNode class is defined as: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right

Example 1

Input: root = TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20))) ops = ["get_next", "has_next", "get_next", "has_next", "get_next", "has_next", "get_next", "has_next", "get_next", "has_next"]

Output: [5, True, 10, True, 12, True, 15, True, 20, False]

Explanation: In-order traversal: [5, 10, 12, 15, 20]. Each get_next returns the next value; has_next returns True until the traversal is finished.

Example 2

Input: root = TreeNode(8, TreeNode(4, None, TreeNode(6)), TreeNode(10)) ops = ["has_next", "get_next", "has_next", "get_next", "has_next", "get_next", "has_next", "get_next", "has_next"]

Output: [True, 4, True, 6, True, 8, True, 10, False]

Explanation: In-order traversal: [4, 6, 8, 10].

Constraints

  • 1 <= number of nodes in BST <= 100000
  • 0 <= node value <= 1000000
  • At most 100000 calls to has_next() and get_next()
Python (current runtime)

Case 1

Input: root = TreeNode(2, None, TreeNode(3)) ops = ["has_next", "get_next", "has_next", "get_next", "has_next"]

Expected: [True, 2, True, 3, False]

Case 2

Input: root = TreeNode(1) ops = ["has_next", "get_next", "has_next"]

Expected: [True, 1, False]

Case 3

Input: root = TreeNode(7, TreeNode(3), TreeNode(9, None, TreeNode(11))) ops = ["get_next", "has_next", "get_next", "has_next", "get_next", "has_next", "get_next", "has_next"]

Expected: [3, True, 7, True, 9, True, 11, False]