Introduction

Diameter of Binary Tree means:

  • finding longest path
  • between any two nodes
  • in binary tree

The path:

  • may or may not
    pass through root

Diameter represents:

  • maximum number of edges
    between two nodes

Example:

        1      /   \
2 3
/ \
4 5
Diameter:
3

Explanation:

Longest path:4 → 2 → 1 → 3

Total edges:
3

This problem is one of the most important applications of:

 DFS Traversal

Constraints

1 <= Number of Nodes <= 10^5

Approach : Recursive DFS Solution

Explanations:

Explanation:

The idea is:

  • calculate subtree heights
  • update maximum diameter

Steps:

  1. Find left subtree height.
  2. Find right subtree height.
  3. Calculate path length.
  4. Update maximum diameter.
  5. Return subtree height.

Formula:

leftHeight + rightHeight 

This approach:

  • uses DFS recursion
  • combines height calculation and diameter update

Dry Run

Visit:1

Left height:
2
Right height:
1
Diameter through node:
3
Update maximum diameter:
3
Output:
3

Practice :

Complexity Analysis :

Time Complexity:- O(n)Explanation :
Every tree node is visited once.

Space Complexity:- O(h)
Explanation : Recursion stack depends on tree height.

Why This Problem is Important

This problem builds the foundation for:

  • DFS traversal
  • Tree recursion
  • Height calculation
  • Recursive tree processing
  • Binary tree analysis

Real-World Applications

Diameter concepts are used in:

  • Network routing
  • Graph analysis
  • Tree optimization
  • Social network systems
  • Hierarchical processing

Common Beginner Mistakes

  • Confusing nodes and edges
  • Incorrect diameter update
  • Missing height calculation
  • Wrong recursion flow
  • Forgetting global variable reset

Interview Tip

Interviewers often expect:

  • DFS understanding
  • recursion explanation
  • height calculation logic
  • diameter update clarity

Always explain:

  • subtree heights
  • recursive traversal
  • longest path calculation

Related Questions

  • Maximum Depth of Binary Tree
  • Balanced Binary Tree
  • Symmetric Tree
  • Tree Height
  • DFS Traversal

Final Takeaway

The Diameter of Binary Tree problem is one of the most important beginner DFS tree problems.

It teaches:

  • DFS recursion
  • subtree height calculation
  • longest path logic
  • recursive tree processing

Understanding this problem builds a strong foundation for:

  • advanced tree problems
  • graph traversal
  • interview-level algorithms.