# 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

###


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coding-9.gitbook.io/untitled/trees/binary-tree/easy/543.-diameter-of-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
