Bird
Raised Fist0

Which line contains the subtle bug that can cause incorrect tree construction or infinite loops?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Construct Tree from Preorder and Inorder
Consider the following buggy code snippet for building a binary tree from preorder and inorder traversals. Which line contains the subtle bug that can cause incorrect tree construction or infinite loops?
ALine where stack is initialized with root
BLine inside if block missing stack.append(node.left)
CLine where root is initialized with preorder[0]
DLine inside else block where inorder_index is incremented
Step-by-Step Solution
  1. Step 1: Identify missing operation

    Inside the if block, after creating node.left, the new node is not pushed onto the stack.
  2. Step 2: Consequences of missing stack append

    Without pushing, the algorithm loses track of the left subtree root, causing incorrect tree or infinite loops.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Stack must track all nodes to correctly build tree [OK]
Quick Trick: Always push newly created nodes to stack to track subtree roots [OK]
Common Mistakes:
MISTAKES
  • Forgetting to push left child nodes
  • Incorrectly incrementing inorder_index
  • Misinitializing root or stack
Trap Explanation:
PITFALL
  • Missing stack append looks like a minor omission but breaks the entire iterative logic.
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of stack role in iterative tree construction.
Master "Construct Tree from Preorder and Inorder" 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