| | | | | |

ADT-Based Iterators

Work for 2-D alternative (no parent pointers)

  • Iterator has private control data structure (stack or queue)
  • Similar to use of Stack/Queue in Depth/Breadth-First Search
  • Preorder, Inorder, Postorder: DFS in the tree, use control Stack
  • LevelOrder: BFS in tree, use control Queue
  • Inorder can and should be full bidirectional iterator
    1. Often becomes the official Set::Iterator type
    2. Control stack consists of path from root to location, so should have modest size O(log n)
    3. Can go forward or backward, algorithm is the same (except for interchanging right/left)
    4. Making copies means copying the control stack, but the stack is not too big, since it is a path from root to the current location
  • Levelorder is typically forward iterator only [++ but not --]:
    1. Can't put the toothpaste (Pop'd locations) back in the tube (the queue)
    2. Useful for specialized applications, for example preserving tree structure in a file
    3. Sometimes copy disabled [++() but not ++(int)]:
      The queue can be huge - Ω(n) even in a balanced BST
  • Pre- and Post- can also be full bidirectional iterator types
    1. Control stack is modest size, copying is not inefficient
    2. "preorder increment" (operator++) is the same algorithm as "postorder decrement" (operator--), except that right/left are interchanged. Similarly, "preorder decrement" is a left-handed version of "postorder increment".

| | Top of Page | 14. BST Iterators - 22 of 41