Bird
Raised Fist0

Given the tree: 1 / \ 2 3 / 4 What is the final value of the variable diameter after the function completes?

easy🧾 Code Trace Q12 of Q15
Tree: Depth-First Search - Diameter of Binary Tree
Consider the following iterative postorder traversal code to compute the diameter of a binary tree. Given the tree: 1 / \ 2 3 / 4 What is the final value of the variable diameter after the function completes?
A2
B4
C1
D3
Step-by-Step Solution
Solution:
  1. Step 1: Trace heights and diameter updates for each node.

    Node 4: height=1, diameter=0; Node 2: left=1 (node4), right=0, diameter=max(0,1)=1; Node 3: height=1, diameter=1; Node 1: left=2 (node2), right=1 (node3), diameter=max(1,2+1=3)=3.
  2. Step 2: Verify final diameter value returned.

    The diameter is the maximum sum of left and right heights at any node, which is 3 edges, so the longest path length is 3 edges.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Longest path is from node 4 to node 3 with length 3 edges [OK]
Quick Trick: Diameter counts edges, not nodes [OK]
Common Mistakes:
MISTAKES
  • Confusing diameter as number of nodes
  • Off-by-one in height calculation
  • Missing right subtree height
Trap Explanation:
PITFALL
  • Counting nodes instead of edges leads to off-by-one errors in diameter value.
Interviewer Note:
CONTEXT
  • Checks candidate's ability to mentally execute iterative postorder and understand diameter definition.
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