Bird
Raised Fist0

Consider the CompositeIterator traversing a composite with a single leaf node named 'X'. What is the output of the following code?

medium🧾 Code Trace Q4 of Q15
OOP & Design Patterns - Iterator & Composite Pattern - Traversal Abstractions
Consider the CompositeIterator traversing a composite with a single leaf node named 'X'. What is the output of the following code?
A['Y']
B['X']
C[]
DError due to empty stack
Step-by-Step Solution
Solution:
  1. Step 1: Initialize stack with reversed children

    Stack contains one leaf 'X'.
  2. Step 2: Iterate and collect names

    hasNext() true once, next() returns 'X', then hasNext() false.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Single leaf traversal returns ['X'] [OK]
Quick Trick: Single leaf -> iterator returns that leaf once [OK]
Common Mistakes:
MISTAKES
  • Assuming empty output for single leaf
  • Expecting error on single element
  • Confusing leaf name
Trap Explanation:
PITFALL
  • Candidates may think iterator fails on single element or returns wrong name.
Interviewer Note:
CONTEXT
  • Tests boundary condition handling in iterator traversal.
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