Bird
Raised Fist0
DSA C++programming~10 mins

Diameter of Binary Tree in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Diameter of Binary Tree
Start at root node
↓
Compute left subtree height
↓
Compute right subtree height
↓
Calculate diameter through current node = left height + right height
↓
Update max diameter if current diameter is larger
↓
Return height of current node = max(left height, right height) + 1
↓
Repeat for left and right child nodes recursively
↓
Final max diameter stored after full traversal
↓
End
The diameter is found by recursively computing heights of left and right subtrees at each node, updating the maximum diameter found as the sum of these heights.
Execution Sample
DSA C++
int diameter = 0;
int height(TreeNode* node) {
  if (!node) return 0;
  int left = height(node->left);
  int right = height(node->right);
  diameter = max(diameter, left + right);
  return max(left, right) + 1;
}
This code recursively calculates the height of each subtree and updates the diameter as the sum of left and right subtree heights at each node.
Execution Table
StepOperationNode VisitedLeft HeightRight HeightDiameter UpdateDiameter ValueVisual State
1Visit root1??Calculate left and right heights0Root(1)
2Visit left child2??Calculate left and right heights0Root(1) -> Left(2)
3Visit left-left child400Diameter = max(0,0+0)=00Root(1) -> Left(2) -> Left(4)
4Return height from node 4400--Height=1 at node 4
5Visit left-right child500Diameter = max(0,0+0)=00Root(1) -> Left(2) -> Right(5)
6Return height from node 5500--Height=1 at node 5
7Calculate height at node 2211Diameter = max(0,1+1)=22Height=2 at node 2
8Visit right child3??Calculate left and right heights2Root(1) -> Right(3)
9Visit right-left child600Diameter = max(2,0+0)=22Root(1) -> Right(3) -> Left(6)
10Return height from node 6600--Height=1 at node 6
11Visit right-right child700Diameter = max(2,0+0)=22Root(1) -> Right(3) -> Right(7)
12Return height from node 7700--Height=1 at node 7
13Calculate height at node 3311Diameter = max(2,1+1)=22Height=2 at node 3
14Calculate height at root node 1122Diameter = max(2,2+2)=44Height=3 at root
15End----4Final diameter = 4
💡 All nodes visited, diameter updated to maximum sum of left and right subtree heights.
Variable Tracker
VariableStartAfter Step 3After Step 6After Step 7After Step 10After Step 13After Step 14Final
diameter00022244
height(node 4)?1111111
height(node 5)??111111
height(node 2)???22222
height(node 6)????1111
height(node 7)????1111
height(node 3)?????222
height(root 1)??????33
Key Moments - 3 Insights
Why do we add left and right subtree heights to update the diameter?
Because the diameter is the longest path between two nodes, which passes through the current node as the sum of left and right subtree heights (see Step 7 and Step 14 in execution_table).
Why do we return max(left height, right height) + 1 as the height?
Height is the longest path from current node down to a leaf, so we take the larger subtree height and add 1 for the current node (see Steps 4, 6, 7, 13, 14).
Why does the diameter update happen before returning height?
Because diameter depends on both left and right subtree heights at the current node, so we must compute and update diameter before returning height (see Steps 7 and 14).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 7, what is the diameter value after visiting node 2?
A1
B2
C0
D4
💡 Hint
Check the 'Diameter Value' column at Step 7 in execution_table.
At which step does the diameter first update to 4?
AStep 13
BStep 7
CStep 14
DStep 15
💡 Hint
Look at the 'Diameter Update' and 'Diameter Value' columns in execution_table for the largest update.
If the left subtree of root had height 1 instead of 2, how would the final diameter change?
AIt would decrease by 1
BIt would remain 4
CIt would increase by 1
DIt would become 2
💡 Hint
Diameter is sum of left and right heights at root (see Step 14 in execution_table).
Concept Snapshot
Diameter of Binary Tree:
- Diameter = longest path between any two nodes
- At each node, diameter = left height + right height
- Use recursion to get heights of left and right subtrees
- Update max diameter during traversal
- Return height = max(left, right) + 1
- Final diameter stored in global variable
Full Transcript
The diameter of a binary tree is the longest path between any two nodes. We find it by visiting each node and calculating the height of its left and right subtrees. At each node, we add these heights to get the diameter passing through that node. We keep track of the maximum diameter found so far. The height returned from each node is one plus the maximum height of its subtrees. This process is done recursively starting from the root. The final diameter is the maximum sum of left and right subtree heights found during the traversal.

Practice

(1/5)
1. What does the diameter of a binary tree represent?
easy
A. The longest path between any two nodes in the tree
B. The height of the tree
C. The number of leaf nodes
D. The total number of nodes in the tree

Solution

  1. Step 1: Understand the diameter definition

    The diameter is the longest path between any two nodes, not just from root to leaf.
  2. Step 2: Differentiate from height and node count

    Height is longest root-to-leaf path; node count and leaf count are unrelated to diameter.
  3. Final Answer:

    The longest path between any two nodes in the tree -> Option A
  4. Quick Check:

    Diameter = longest node-to-node path [OK]
Hint: Diameter is longest path between any two nodes [OK]
Common Mistakes:
  • Confusing diameter with tree height
  • Thinking diameter counts nodes instead of edges
  • Assuming diameter is number of leaf nodes
2. Which of the following is the correct C++ function signature to compute the diameter of a binary tree node?
easy
A. int diameter(TreeNode& root);
B. void diameter(TreeNode root);
C. int diameter(TreeNode root);
D. int diameter(TreeNode* root);

Solution

  1. Step 1: Understand pointer usage in tree nodes

    Binary trees are usually handled with pointers to nodes, so TreeNode* is correct.
  2. Step 2: Check return type and parameter correctness

    Diameter returns an int, and parameter should be pointer, not value or reference for typical tree traversal.
  3. Final Answer:

    int diameter(TreeNode* root); -> Option D
  4. Quick Check:

    Pointer parameter with int return [OK]
Hint: Use pointer parameter and int return type [OK]
Common Mistakes:
  • Passing node by value instead of pointer
  • Using void return type instead of int
  • Passing node by reference unnecessarily
3. What is the output of the following code snippet computing diameter?
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

int height(TreeNode* root) {
  if (!root) return 0;
  return 1 + std::max(height(root->left), height(root->right));
}

int diameter(TreeNode* root) {
  if (!root) return 0;
  int leftHeight = height(root->left);
  int rightHeight = height(root->right);
  int leftDiameter = diameter(root->left);
  int rightDiameter = diameter(root->right);
  return std::max(leftHeight + rightHeight, std::max(leftDiameter, rightDiameter));
}

int main() {
  TreeNode* root = new TreeNode(1);
  root->left = new TreeNode(2);
  root->right = new TreeNode(3);
  root->left->left = new TreeNode(4);
  root->left->right = new TreeNode(5);
  std::cout << diameter(root);
  return 0;
}
medium
A. 6
B. 4
C. 3
D. 5

Solution

  1. Step 1: Calculate heights of left and right subtrees

    Left subtree height: max height of nodes 2->4 or 2->5 is 2; right subtree height (node 3) is 1.
  2. Step 2: Calculate diameter candidates and choose max

    Diameter candidates: leftHeight + rightHeight = 2 + 1 = 3; leftDiameter and rightDiameter are computed recursively. LeftDiameter is 2 (path 4-2-5), rightDiameter is 0. Max is 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Longest path length = 3 edges [OK]
Hint: Sum left and right subtree heights for diameter [OK]
Common Mistakes:
  • Confusing height with diameter
  • Counting nodes instead of edges
  • Ignoring recursive diameter calls
4. Identify the bug in this diameter function and select the fix:
int diameter(TreeNode* root) {
  if (!root) return 0;
  int leftHeight = height(root->left);
  int rightHeight = height(root->right);
  int leftDiameter = diameter(root->left);
  int rightDiameter = diameter(root->right);
  return leftHeight + rightHeight;
}
medium
A. Return max of leftDiameter and rightDiameter only
B. Return max of leftHeight + rightHeight and leftDiameter, rightDiameter
C. Return sum of leftDiameter and rightDiameter
D. Return height of root node

Solution

  1. Step 1: Analyze current return statement

    Currently returns only leftHeight + rightHeight, ignoring recursive diameters from subtrees.
  2. Step 2: Correct return to consider all diameter candidates

    Diameter is max of leftHeight + rightHeight, leftDiameter, and rightDiameter.
  3. Final Answer:

    Return max of leftHeight + rightHeight and leftDiameter, rightDiameter -> Option B
  4. Quick Check:

    Include all diameter candidates [OK]
Hint: Return max of height sum and subtree diameters [OK]
Common Mistakes:
  • Ignoring recursive diameter calls
  • Returning sum of diameters incorrectly
  • Returning height instead of diameter
5. Given a binary tree where each node has a value, how would you modify the diameter function to return the maximum sum of node values on any path between two nodes instead of the number of edges?
hard
A. Change height function to return max sum of node values and update diameter to use sums instead of heights
B. Use the same diameter function but multiply the result by node values
C. Calculate diameter normally and add all node values in the tree
D. Return the maximum node value in the tree as diameter

Solution

  1. Step 1: Modify height to return max sum of node values

    Instead of counting edges, height returns max sum from node to leaf including node values.
  2. Step 2: Update diameter to use sums from left and right subtrees

    Diameter becomes max of left sum + right sum and recursive diameters, reflecting max path sum.
  3. Final Answer:

    Change height function to return max sum of node values and update diameter to use sums instead of heights -> Option A
  4. Quick Check:

    Use sums in height and diameter for max path value [OK]
Hint: Use sums in height and diameter for max path value [OK]
Common Mistakes:
  • Multiplying diameter by node values incorrectly
  • Adding all node values regardless of path
  • Returning max node value instead of path sum
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard