Problem 405418 · medium · Level 04 Non-Linear Data Structures

Ascending Cursor Over a Search Tree

binary search tree · iterator · stack · class design

Implement a class BSTCursor that walks a binary search tree in ascending order, one value at a time:

  • BSTCursor(root) prepares the cursor (the tree may be empty);
  • next() returns the next smallest value not yet returned (only called when one exists);
  • has_next() returns True if another value remains.

Tests drive the class with run_ops: the first operation constructs the object, and the result list holds None for the constructor.

Examples

     10
    /  \
   4    17
    \   /
     6 13

ops  = ["BSTCursor", "next", "next", "has_next", "next", "next", "next", "has_next"]
args = [[build_tree([10, 4, 17, None, 6, 13])], [], [], [], [], [], [], []]
Output: [None, 4, 6, True, 10, 13, 17, False]

Constraints

  • 0 <= number of nodes <= 3000
  • next and has_next should run in amortised O(1) time using O(h) memory; do not copy the whole tree into a list

Goals

  • Produce inorder values lazily, one per call
  • Keep only O(h) memory by storing the pending left spine
Starting Python…