Bird
Raised Fist0

Consider the following buggy code snippet for building a tree from inorder and postorder traversals. Which line contains the subtle bug that can cause incorrect tree construction or runtime errors?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Construct Tree from Inorder and Postorder
Consider the following buggy code snippet for building a tree from inorder and postorder traversals. Which line contains the subtle bug that can cause incorrect tree construction or runtime errors?
ALine creating root node with postorder[-1]
BLine initializing inorder_index to 0
CLine attaching node as right child
DLine popping from stack inside while loop
Step-by-Step Solution
  1. Step 1: Identify inorder_index initialization

    inorder_index should start at the last index (len(inorder) - 1) because postorder is processed from end to start.
  2. Step 2: Consequences of wrong initialization

    Starting at 0 causes incorrect comparisons and popping logic, leading to wrong tree structure or runtime errors.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct inorder_index initialization is critical for stack popping logic [OK]
Quick Trick: inorder_index must start at last index, not zero [OK]
Common Mistakes:
MISTAKES
  • Wrong inorder_index initialization
  • Confusing postorder traversal direction
  • Incorrect stack popping conditions
Trap Explanation:
PITFALL
  • This subtle off-by-one initialization bug passes many tests but breaks on larger inputs.
Interviewer Note:
CONTEXT
  • Tests if candidate can spot subtle index initialization bugs that cause logical errors.
Master "Construct Tree from Inorder and Postorder" 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