# 6.Longest path in an undirected tree

![Longest path 5 (node 5 to node 7)](/files/-MJQKOr-zefq8ZYhZs83)

## Solution : (Using two BFS)

First **BFS to find an endpoint of the longest path** and **second BFS from this endpoint to find the actual longest path.**

```cpp
#include <bits/stdc++.h>

using namespace std;

void bfs(int node, vector<int> v[], vector<bool> &vs, vector<int> &dist)
{
    queue<int> q;
    q.push(node);
    vs[node] = 1;
    dist[node] = 0;

    while (!q.empty())
    {
        int s = q.size();

        int x = q.front();
        q.pop();

        for (auto itr = v[x].begin(); itr != v[x].end(); itr++)
        {
            if (vs[*itr] == 0)
            {
                vs[*itr] = 1;
                q.push(*itr);
                dist[*itr] = dist[x] + 1;
            }
        }
    }
    return;
}

int main()
{

    int n;
    cin >> n;
    vector<int> v[n + 1];

    for (int k = 1; k <= n - 1; k++)
    {
        int a, b;
        cin >> a >> b;
        v[a].push_back(b);
        v[b].push_back(a);
    }

    int max = INT_MIN;
    int idx = -1;
    vector<bool> vs(n + 1);
    vector<int> dist(n + 1);
    bfs(1, v, vs, dist);

    for (int i = 1; i <= n; i++)
    {
        if (dist[i] > max)
        {
            max = dist[i];
            idx = i;
        }
    }

    int temp_max = max;

    vector<bool> vs1(n + 1);
    vector<int> dist1(n + 1);
    bfs(idx, v, vs1, dist1);

    max = INT_MIN;
    idx = -1;

    for (int i = 1; i <= n; i++)
    {
        if (dist1[i] > max)
        {
            max = dist1[i];
            idx = i;
        }
    }

    if (max > temp_max)
    {
        cout << max;
    }
    else
    {
        cout << temp_max;
    }
    return 0;
}

```


---

# 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://soumyajit4419.gitbook.io/ds-algo/graph/5.longest-path-in-an-undirected-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.
