Bird
Raised Fist0

Given a composite with two leaves named 'A' and 'B', what will be the output of iterating over the composite's iterator and collecting the names in order?

easy🧾 Code Trace Q12 of Q15
OOP & Design Patterns - Iterator & Composite Pattern - Traversal Abstractions
Consider the following Python code implementing the Composite pattern with iterators. Given a composite with two leaves named 'A' and 'B', what will be the output of iterating over the composite's iterator and collecting the names in order?
A['B', 'A']
B['A', 'B']
C['root', 'A', 'B']
D['A']
Step-by-Step Solution
  1. Step 1: Trace the stack initialization

    The CompositeIterator reverses children, so stack = [leafB, leafA].
  2. Step 2: Trace iteration order

    Pop leafA first (stack now [leafB]), then leafB (stack empty). Names collected in order: 'A', then 'B'.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Reversing children in stack causes correct iteration order [OK]
Quick Trick: Stack reversed children -> correct iteration order [OK]
Common Mistakes:
MISTAKES
  • Assuming original order without reversing stack
  • Including composite node name in output
Trap Explanation:
PITFALL
  • Reversing children in stack ensures correct iteration order, avoiding confusion.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute iterator code and understand traversal order.
Master "Iterator & Composite Pattern - Traversal Abstractions" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes