**Physical Address**

304 North Cardinal St.

Dorchester Center, MA 02124

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.

**Example 1:**

```
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
```

**Example 2:**

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

**Constraints:**

- The number of nodes in the tree is in the range
`[1, 10`

.^{4}] `-100 <= Node.val <= 100`

```
public class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return max;
}
private int maxDepth(TreeNode root) {
if (root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
max = Math.max(max, left + right);
return Math.max(left, right) + 1;
}
}
```

```
int diameterOfBinaryTree(TreeNode* root) {
int d=0;
rec(root, d);
return d;
}
int rec(TreeNode* root, int &d) {
if(root == NULL) return 0;
int ld = rec(root->left, d);
int rd = rec(root->right, d);
d=max(d,ld+rd);
return max(ld,rd)+1;
}
```

```
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
def depth(p):
if not p: return 0
left, right = depth(p.left), depth(p.right)
self.ans = max(self.ans, left+right)
return 1 + max(left, right)
depth(root)
return self.ans
```

In our experience, we suggest you solve this Diameter of Binary Tree LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Diameter of Binary Tree LeetCode Solution

I hope this Diameter of Binary Tree LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

**More Coding Solutions >>**