Bird
Raised Fist0

Identify the subtle bug in the following iterative preorder traversal code snippet that causes incorrect traversal order:

medium🐞 Bug Identification Q7 of Q15
Tree: Depth-First Search - Binary Tree Preorder Traversal
Identify the subtle bug in the following iterative preorder traversal code snippet that causes incorrect traversal order:
APushing left child before right child causes right subtree to be visited first
BNot checking for null root causes runtime error
CAppending node value before popping causes wrong order
DUsing a stack instead of a queue causes incorrect traversal
Step-by-Step Solution
Solution:
  1. Step 1: Trace push order

    Left child pushed before right child means right child is popped first (LIFO).
  2. Step 2: Resulting traversal order

    Right subtree visited before left subtree, violating preorder's root-left-right order.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Stack LIFO reverses push order [OK]
Quick Trick: Push right child before left to visit left first [OK]
Common Mistakes:
MISTAKES
  • Pushing left before right without reversing order
Trap Explanation:
PITFALL
  • Candidates overlook stack LIFO behavior causing reversed subtree visits.
Interviewer Note:
CONTEXT
  • Tests candidate's understanding of stack order impact on traversal.
Master "Binary Tree Preorder Traversal" in Tree: Depth-First Search

3 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 Tree: Depth-First Search Quizzes