> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/trees/binary-tree/easy/543.-diameter-of-binary-tree.md).

# 543. Diameter of Binary Tree

## Problem Statement

<br>

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.

&#x20;

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg)

<pre><code><strong>Input: root = [1,2,3,4,5]
</strong><strong>Output: 3
</strong><strong>Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: root = [1,2]
</strong><strong>Output: 1
</strong></code></pre>

&#x20;

**Constraints:**

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

## Intuition

```
Find the max of l+r at each step
Basically longest node to longest
```

### Links

<https://leetcode.com/problems/diameter-of-binary-tree/description/>

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution {
public:
    int maxi=0;
    int find_ans(TreeNode* root){
        if(root==nullptr)
            return 0;

        int l = find_ans(root->left);
        int r = find_ans(root->right);

        maxi = max(maxi, l+r);

        return 1 + max(l,r);
    }

    int diameterOfBinaryTree(TreeNode* root) {
        find_ans(root);
        return maxi;
    }
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###
