Iterator for Trees
A tree iterator encapsulates the current position (often with an explicit stack for inorder). This keeps the internal representation hidden and algorithms work against hasNext/next.
Fail-fast behavior is analogous to lists: structural changes during iteration are risky.
Where used
Lazy traversal of large hierarchies, UI tree models, termination upon finding a match without needing to materialize the entire structure.
Depth
A tree iterator must store the unvisited control state between calls. For a sorted output of a search tree, it typically maintains a path of open nodes; after an output, the corresponding child subtree is revealed.
Each node is stored once and removed once. As a result, the total costs are linear, even though a single next call can add several path nodes. These peaks are distributed over the entire traversal.
Structural changes during iteration can invalidate paths. A fail-fast check detects many such changes but does not guarantee synchronization.
Difficulty levels
- Specify the stored path after each
next. - Justify the amortized costs of a complete traversal.
- Specify the behavior of an iterator on changes.
Pitfalls
Simply storing the last output node is insufficient without parent references. hasNext should neither output nodes nor consume the traversal state.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users