Bird
0
0

When designing an iterator for a tree structure to traverse nodes in depth-first order, which design best aligns with the Iterator pattern?

hard📝 Trade-off Q8 of 15
LLD - Behavioral Design Patterns — Part 1

When designing an iterator for a tree structure to traverse nodes in depth-first order, which design best aligns with the Iterator pattern?

AFlatten the tree into a list before iteration
BExpose the tree's internal node list and let clients handle traversal
CUse recursion in the client code to traverse the tree
DImplement a stack-based iterator that manages traversal state internally
Step-by-Step Solution
Solution:
  1. Step 1: Understand Iterator pattern goal

    The pattern encapsulates traversal logic inside the iterator, hiding internal structure.
  2. Step 2: Evaluate options

    Implement a stack-based iterator that manages traversal state internally uses a stack-based iterator managing traversal internally, fitting the pattern. Options B and C expose internals or push traversal to clients. Flatten the tree into a list before iteration breaks encapsulation by flattening upfront.
  3. Final Answer:

    Implement a stack-based iterator that manages traversal state internally -> Option D
  4. Quick Check:

    Iterator encapsulates traversal, not exposes or delegates it [OK]
Quick Trick: Iterator hides traversal logic inside, uses stack for DFS [OK]
Common Mistakes:
MISTAKES
  • Exposing internal tree structure to clients
  • Using client-side recursion instead of iterator
  • Pre-flattening tree breaking encapsulation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes