LeetCode 543: Diameter of Binary Tree – Java DFS Solution Explained

Learn how to solve LeetCode 543 Diameter of Binary Tree using optimized DFS recursion in Java. Includes brute force approach, optimized solution, intuition, dry run, complexity analysis, interview explanation, and common mistakes.

Krishna Shrivastava
1 views
LinkedInGithubX
0
0
LeetCode 543: Diameter of Binary Tree – Java DFS Solution Explained
Listen to articleAudio version
Ad
Advertisement

Introduction

LeetCode 543 – Diameter of Binary Tree is one of the most popular binary tree interview problems.

This problem teaches:

  1. Depth First Search (DFS)
  2. Tree height calculation
  3. Recursive traversal
  4. Bottom-up recursion
  5. Tree optimization techniques

It is extremely important because it introduces a very common pattern in tree problems:

Use recursion to calculate subtree heights while simultaneously updating a global answer.

This same idea is used in:

  1. Balanced Binary Tree
  2. Maximum Path Sum
  3. Longest ZigZag Path
  4. Tree DP problems

Problem Link

🔗 https://leetcode.com/problems/diameter-of-binary-tree/

Problem Statement

Given the root of a binary tree:

Return:

Length of the diameter of the tree

The diameter is:

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

This path:

  1. May pass through the root
  2. May not pass through the root

Important Note

The diameter is measured in:

EDGES

not nodes.

Example 1

Input

root = [1,2,3,4,5]

Tree:

1
/ \
2 3
/ \
4 5

Output

3

Explanation:

Longest path:

4 → 2 → 1 → 3

Edges count:

3

Example 2

Input

root = [1,2]

Tree:

1
/
2

Output:

1

Understanding Diameter

At every node:

Possible longest path through that node is:

left subtree height + right subtree height

Why?

Because:

  1. One side contributes left edges
  2. Other side contributes right edges

Together they form a path.

Key Observation

For every node:

Diameter through node
=
leftHeight + rightHeight

We compute this for all nodes.

Maximum among them becomes answer.

Brute Force Approach

Intuition

For every node:

  1. Calculate left subtree height
  2. Calculate right subtree height
  3. Compute diameter
  4. Recursively repeat for children

Brute Force Complexity

Height gets recalculated repeatedly.

Time Complexity

O(N²)

Space Complexity

O(H)

where:

H = tree height

Optimized DFS Approach

Instead of separately calculating:

  1. Height
  2. Diameter

We calculate both in one DFS traversal.

Core Idea

While calculating subtree height:

We also update:

max diameter

This avoids repeated traversal.

Java Solution

class Solution {

int max = Integer.MIN_VALUE;

public int solve(TreeNode roo) {

if(roo == null)
return 0;

int left = solve(roo.left);

int right = solve(roo.right);

max = Math.max(max, left + right);

return 1 + Math.max(left, right);
}

public int diameterOfBinaryTree(TreeNode root) {

solve(root);

return max;
}
}

Cleaner Optimized Version

class Solution {

int diameter = 0;

public 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 1 + Math.max(left, right);
}

public int diameterOfBinaryTree(TreeNode root) {

height(root);

return diameter;
}
}

Why This Works

At every node:

  1. Find left subtree height
  2. Find right subtree height
  3. Compute:
left + right
  1. Update global maximum diameter
  2. Return current subtree height upward

Dry Run

Input

1
/ \
2 3
/ \
4 5

Step 1

Leaf nodes:

4 → height = 1
5 → height = 1
3 → height = 1

Step 2

At node:

2

Left height:

1

Right height:

1

Diameter through node:

1 + 1 = 2

Update:

max = 2

Height of node 2:

2

Step 3

At root:

1

Left height:

2

Right height:

1

Diameter:

2 + 1 = 3

Update:

max = 3

Final Answer

3

Recursive Visualization

height(1)
├── height(2)
│ ├── height(4)
│ └── height(5)
└── height(3)

Diameter gets updated during return phase.

Time Complexity Analysis

Optimized DFS Solution

Time Complexity

O(N)

because every node is visited once.

Space Complexity

O(H)

where:

H = tree height

Worst case:

O(N)

for skewed tree.

Brute Force vs Optimized

ApproachTime ComplexitySpace Complexity
Brute ForceO(N²)O(H)
Optimized DFSO(N)O(H)

Interview Explanation

In interviews, explain:

While recursively calculating subtree heights, we simultaneously compute the maximum possible path passing through every node.

This demonstrates:

  1. DFS understanding
  2. Bottom-up recursion
  3. Optimization skills
  4. Tree DP thinking

Common Mistakes

1. Counting Nodes Instead of Edges

Diameter measures:

edges

not nodes.

2. Forgetting Global Variable

Diameter must be updated across all nodes.

3. Returning Diameter Instead of Height

Recursive function should return:

height

not diameter.

FAQs

Q1. Does diameter always pass through root?

No.

It can exist completely inside a subtree.

Q2. Why use DFS?

Because height calculation naturally follows recursive depth traversal.

Q3. Why update diameter globally?

Because longest path may occur at any node.

Q4. Is this problem important for interviews?

Very important.

It is one of the most common recursive tree questions.

Conclusion

LeetCode 543 is one of the best problems for learning recursive tree optimization.

It teaches:

  1. DFS traversal
  2. Height calculation
  3. Bottom-up recursion
  4. Global answer tracking

The key insight is:

Diameter through a node equals left subtree height + right subtree height.

Once you understand this pattern, many advanced binary tree problems become much easier.

Ai Assistant Kas