DEV Community

Jaspreet singh
Jaspreet singh

Posted on

Diameter of a Binary Tree

Problem Statement

Given the root of a binary tree, return the diameter of the tree.

The diameter is the length of the longest path between any two nodes in the tree.

Note: The path may or may not pass through the root.


Brute Force Intuition

In an interview, you can explain it like this:

For every node, calculate the height of its left subtree and right subtree. The diameter passing through that node is:

Left Height + Right Height
Enter fullscreen mode Exit fullscreen mode

Take the maximum among all nodes.

The problem is that height is recomputed for every node, leading to repeated work.

Complexity

  • Time Complexity: O(N²)
  • Space Complexity: O(H)

Brute Force Code

class Solution {

    public int diameterOfBinaryTree(TreeNode root) {

        if (root == null)
            return 0;

        int leftHeight = height(root.left);

        int rightHeight = height(root.right);

        int currentDiameter =
                leftHeight + rightHeight;

        int leftDiameter =
                diameterOfBinaryTree(root.left);

        int rightDiameter =
                diameterOfBinaryTree(root.right);

        return Math.max(currentDiameter,
                Math.max(leftDiameter,
                         rightDiameter));
    }

    private int height(TreeNode root) {

        if (root == null)
            return 0;

        return 1 + Math.max(
                height(root.left),
                height(root.right));
    }
}
Enter fullscreen mode Exit fullscreen mode

Moving Towards the Optimal Approach

Notice that while computing:

Height
Enter fullscreen mode Exit fullscreen mode

we already visit every node exactly once.

Why calculate height separately?

Instead,

while returning the height,

also update the maximum diameter.

One DFS can compute both.


Pattern Recognition

Whenever you see:

  • Diameter
  • Longest Path
  • Height of Tree

Think:

Postorder DFS


Key Observation

For every node:

Longest Path Through Node

=

Left Height

+

Right Height
Enter fullscreen mode Exit fullscreen mode

At the same time,

return:

Current Height

=

1 + max(Left Height, Right Height)
Enter fullscreen mode Exit fullscreen mode

Optimal Approach

Step 1

Recursively compute:

Left Height
Enter fullscreen mode Exit fullscreen mode

Step 2

Recursively compute:

Right Height
Enter fullscreen mode Exit fullscreen mode

Step 3

Update:

diameter = Math.max(diameter,
                    leftHeight + rightHeight);
Enter fullscreen mode Exit fullscreen mode

Step 4

Return:

1 + Math.max(leftHeight, rightHeight);
Enter fullscreen mode Exit fullscreen mode

Optimal Java Solution

class Solution {

    int diameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {

        height(root);

        return diameter;
    }

    private int height(TreeNode root) {

        if (root == null)
            return 0;

        int leftHeight = height(root.left);

        int rightHeight = height(root.right);

        diameter = Math.max(diameter,
                            leftHeight + rightHeight);

        return 1 + Math.max(leftHeight,
                            rightHeight);
    }
}
Enter fullscreen mode Exit fullscreen mode

Dry Run

        1
       / \
      2   3
     / \
    4   5
Enter fullscreen mode Exit fullscreen mode

Node 4

Left = 0

Right = 0

Height = 1

Diameter = 0
Enter fullscreen mode Exit fullscreen mode

Node 5

Height = 1
Enter fullscreen mode Exit fullscreen mode

Node 2

Left Height = 1

Right Height = 1

Diameter = 2

Height = 2
Enter fullscreen mode Exit fullscreen mode

Root 1

Left Height = 2

Right Height = 1

Diameter =

2 + 1

=

3
Enter fullscreen mode Exit fullscreen mode

Final Answer:

3
Enter fullscreen mode Exit fullscreen mode

Path:

4 → 2 → 1 → 3
Enter fullscreen mode Exit fullscreen mode

Why One DFS Works?

Each recursive call already computes the height of its subtree.

While returning that height,

we can immediately compute the longest path passing through the current node.

This eliminates repeated height calculations.

Every node is visited exactly once.


Complexity Analysis

Metric Complexity
Time Complexity O(N)
Space Complexity O(H)

Where:

  • N = Number of Nodes
  • H = Height of the Tree

Interview One-Liner

Compute subtree heights using postorder DFS and update the diameter at each node as the sum of its left and right subtree heights.


Pattern Learned

Postorder DFS

↓

Left Height

↓

Right Height

↓

Update Diameter

↓

Return Height
Enter fullscreen mode Exit fullscreen mode

Similar Problems

  • Diameter of Binary Tree
  • Maximum Depth of Binary Tree
  • Balanced Binary Tree
  • Binary Tree Maximum Path Sum
  • Longest Univalue Path

Memory Trick

Think:

Go Left

↓

Go Right

↓

Diameter = Left + Right

↓

Return Height
Enter fullscreen mode Exit fullscreen mode

Mental Model

Leaf

↓

Returns Height

↓

Parent

↓

Updates Diameter

↓

Returns Height

↓

Repeat
Enter fullscreen mode Exit fullscreen mode

Whenever you hear:

"Diameter of Binary Tree"

your brain should immediately think:

Postorder DFS + Height Calculation

Top comments (0)