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 TraversalConstraints
1 <= Number of Nodes <= 10^5Approach : Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- calculate subtree heights
- update maximum diameter
Steps:
- Find left subtree height.
- Find right subtree height.
- Calculate path length.
- Update maximum diameter.
- 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 :