Bird
Raised Fist0
DSA Javaprogramming~30 mins

Diameter of Binary Tree in DSA Java - Build from Scratch

Choose your learning style10 modes available
Diameter of Binary Tree
📖 Scenario: You are working on a program that analyzes the structure of a family tree. Each person is represented as a node in a binary tree, where the left and right children represent descendants. You want to find the longest path between any two people in this family tree, which is called the diameter of the tree.
🎯 Goal: Build a Java program that calculates the diameter of a binary tree. The diameter is the number of nodes on the longest path between any two nodes in the tree.
📋 What You'll Learn
Create a binary tree with the exact structure given
Add a helper variable to track the maximum diameter found
Write a recursive function to calculate the height of each node and update the diameter
Print the diameter of the binary tree
💡 Why This Matters
🌍 Real World
Finding the diameter of a tree structure is useful in network design, family trees, and organizational charts to understand the longest connection path.
💼 Career
Understanding tree traversal and diameter calculation is important for software engineers working with hierarchical data, optimizing network latency, and solving algorithmic problems.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with an integer val and two TreeNode references called left and right. Then create the exact binary tree below by creating TreeNode objects and linking them:

Root node value: 1
Left child of root: 2
Right child of root: 3
Left child of node 2: 4
Right child of node 2: 5
DSA Java
Hint

Define the TreeNode class first. Then create the root node and assign its left and right children exactly as described.

2
Add a Variable to Track Maximum Diameter
Inside the DiameterBinaryTree class, add a static integer variable called maxDiameter and initialize it to 0. This will keep track of the largest diameter found during traversal.
DSA Java
Hint

Add a static variable maxDiameter inside the DiameterBinaryTree class but outside the main method.

3
Write Recursive Function to Calculate Height and Update Diameter
Add a static method called height that takes a TreeNode parameter called node and returns an integer. This method should:
1. Return 0 if node is null.
2. Recursively find the height of the left subtree by calling height(node.left).
3. Recursively find the height of the right subtree by calling height(node.right).
4. Update maxDiameter with the maximum of its current value and leftHeight + rightHeight + 1.
5. Return the maximum of leftHeight and rightHeight plus 1.
DSA Java
Hint

Use recursion to find the height of left and right children. Update maxDiameter with the sum of left and right heights plus one for the current node.

4
Calculate and Print the Diameter
In the main method, call the height method with root as argument to start the recursion. Then print the value of maxDiameter using System.out.println.
DSA Java
Hint

Call height(root) to start the recursion and then print maxDiameter to see the diameter.

Practice

(1/5)
1. What does the diameter of a binary tree represent?
easy
A. The number of leaf nodes in the tree
B. The length of the longest path between any two nodes in the tree
C. The height of the tree
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, which may or may not pass through the root.
  2. Step 2: Differentiate from other tree properties

    Height is the longest path from root to leaf, leaf count is number of leaves, total nodes is size, none of which define diameter.
  3. Final Answer:

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

    Diameter = Longest path between nodes [OK]
Hint: Diameter is longest path between any two nodes [OK]
Common Mistakes:
  • Confusing diameter with height
  • Thinking diameter counts nodes instead of edges
  • Assuming diameter must pass through root
2. Which of the following Java method signatures correctly represents a recursive function to find the diameter of a binary tree node?
easy
A. public int diameter(int root)
B. public void diameter(TreeNode root)
C. public String diameter(TreeNode root)
D. public int diameter(TreeNode root)

Solution

  1. Step 1: Identify correct parameter type

    The method must accept a TreeNode object representing the root of the tree or subtree.
  2. Step 2: Identify correct return type

    Diameter is a number (int), so return type should be int, not void or String.
  3. Final Answer:

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

    Method returns int and takes TreeNode [OK]
Hint: Diameter method returns int and takes TreeNode [OK]
Common Mistakes:
  • Using void return type for diameter
  • Passing int instead of TreeNode
  • Returning String instead of int
3. Given the following binary tree code snippet, what is the diameter of the tree?
class TreeNode {
  int val;
  TreeNode left, right;
  TreeNode(int x) { val = x; }
}

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);

// Diameter calculation code omitted for brevity
medium
A. 2
B. 5
C. 3
D. 4

Solution

  1. Step 1: Visualize the tree structure

    The tree has root 1, left child 2 with children 4 and 5, and right child 3.
  2. Step 2: Find longest path between any two nodes

    Longest path is from node 4 to node 3 via 2 and 1: path 4->2->1->3 = 3 edges, diameter = 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Longest path length = 3 edges [OK]
Hint: Count edges on longest path between two nodes [OK]
Common Mistakes:
  • Counting nodes instead of edges or vice versa
  • Ignoring paths not passing through root
  • Miscounting edges in path
4. Identify the bug in this diameter calculation method and select the fix:
int diameter = 0;
int height(TreeNode root) {
  if (root == null) return 0;
  int left = height(root.left);
  int right = height(root.right);
  diameter = Math.max(diameter, left + right);
  return Math.max(left, right);
}
medium
A. Return Math.max(left, right) + 1 instead of Math.max(left, right)
B. Initialize diameter inside height method
C. Use diameter = Math.min(diameter, left + right)
D. Return left + right instead of Math.max(left, right)

Solution

  1. Step 1: Understand height calculation

    Height of a node is 1 plus max height of its children, so must add +1.
  2. Step 2: Identify bug in return statement

    Current code returns max(left, right) without +1, so height is underestimated.
  3. Final Answer:

    Return Math.max(left, right) + 1 instead of Math.max(left, right) -> Option A
  4. Quick Check:

    Height = max child height + 1 [OK]
Hint: Height adds 1 to max child height [OK]
Common Mistakes:
  • Forgetting to add +1 in height return
  • Using min instead of max for diameter update
  • Returning sum of left and right as height
5. You want to find the diameter of a binary tree but also print the nodes on the longest path. Which approach is best?
hard
A. Modify the diameter function to store and return the longest path nodes along with diameter
B. Calculate diameter first, then do a separate BFS to find longest path nodes
C. Use only height function and print nodes at max height
D. Count leaf nodes and assume longest path is between two leaves

Solution

  1. Step 1: Understand diameter and path relationship

    Diameter is longest path length; to print nodes, we must track path during diameter calculation.
  2. Step 2: Choose approach that combines diameter and path tracking

    Modifying diameter function to store nodes on longest path is efficient and direct.
  3. Final Answer:

    Modify the diameter function to store and return the longest path nodes along with diameter -> Option A
  4. Quick Check:

    Track path during diameter calc for nodes [OK]
Hint: Track nodes while computing diameter for path [OK]
Common Mistakes:
  • Running BFS separately wastes time
  • Assuming height equals diameter path
  • Counting leaves without path tracking
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