Bird
Raised Fist0

The following code attempts to check if a binary tree is balanced using iterative postorder traversal. Which line contains a subtle bug that can cause incorrect results on an empty tree or null root?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Balanced Binary Tree
The following code attempts to check if a binary tree is balanced using iterative postorder traversal. Which line contains a subtle bug that can cause incorrect results on an empty tree or null root?
ALine 1: Missing check for empty root before traversal
BLine 7: Incorrectly pushing node.left without null check
CLine 12: Comparing last_visited with peek.right incorrectly
DLine 16: Using abs difference without considering null children
Step-by-Step Solution
Solution:
  1. Step 1: Identify handling of empty tree

    The code does not check if root is None before starting traversal, which can cause errors or incorrect results.
  2. Step 2: Verify other lines

    Other lines handle null children safely using heights.get with default 0, and last_visited logic is correct.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing early return for empty root causes bug [OK]
Quick Trick: Always check for empty root before traversal [OK]
Common Mistakes:
MISTAKES
  • Forgetting to handle empty tree as balanced
  • Incorrectly comparing last_visited causing infinite loops
  • Not defaulting heights for null children
Trap Explanation:
PITFALL
  • Option A looks like initialization but missing empty check causes subtle bug; others are correct usage.
Interviewer Note:
CONTEXT
  • Tests if candidate notices edge case handling for empty input in iterative traversal.
Master "Balanced Binary Tree" 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