# Diameter of Binary Tree Leetcode Solution

## Diameter of Binary Tree Leetcode Problem :

Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them.

## Diameter of Binary Tree Leetcode Solution :

### Constraints :

• The number of nodes in the tree is in the range [1, 104].
• -100 <= Node.val <= 100

### Example 1:

• Input: root = [1,2]
• Output: 1

Intuition :

1. Traverse the tree using a depth-first search (DFS) or breadth-first search (BFS) algorithm.
2. For each node, calculate the length of the longest path that passes through that node. This length is equal to the height of the left subtree of the node plus the height of the right subtree of the node, plus one (to count the node itself).
3. The diameter of the tree is equal to the maximum of all of these lengths.

Approach :

1. Start traversing the tree recursively and do work in Post Order.
In the Post Order of every node , calculate diameter and height of the current node.
2. If current diameter is maximum then update the variable used to store the maximum diameter.
3. Return height of current node to the previous recursive call.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others