Bird
Raised Fist0

The following code attempts to compute the diameter of a binary tree. Identify the subtle bug that causes incorrect diameter calculation.

medium🐞 Bug Identification Q7 of Q15
Tree: Depth-First Search - Diameter of Binary Tree
The following code attempts to compute the diameter of a binary tree. Identify the subtle bug that causes incorrect diameter calculation.
ABase case returns 0 instead of -1
BDiameter variable is not declared nonlocal, so updates do not persist
CHeight function returns wrong height calculation
DDiameter is updated only at root node
Step-by-Step Solution
Solution:
  1. Step 1: Check variable scope

    Diameter is assigned inside nested function without nonlocal keyword, so outer diameter is not updated.
  2. Step 2: Effect on diameter calculation

    Diameter remains 0, causing incorrect final result.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing nonlocal causes diameter updates to fail [OK]
Quick Trick: Missing nonlocal -> diameter not updated
Common Mistakes:
MISTAKES
  • Forgetting nonlocal in nested functions
  • Assuming diameter updates persist without scope declaration
Trap Explanation:
PITFALL
  • Candidates overlook variable scope, thinking diameter updates inside nested function affect outer variable.
Interviewer Note:
CONTEXT
  • Tests understanding of Python variable scope in recursive functions
Master "Diameter of 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