a coding task

该篇文章介绍了一个名为`intsolution`的函数,它接受树的平面表示`flattree`,构建一棵树并计算其最大直径(最长路径)。使用深度优先搜索(DFS)递归地找到树的两个端点,返回它们之间的最大路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int solution(int n, vector<vector<int>> flattree) 
requirement :
1. build a tree from flattree.
2. flattree[i] for each valid i contains two elements and represents an edge that connects flattree[i][0] and flattree[i][1].
3. It is guaranteed that given graph is a tree, i.e. it is connected and has no cycles.
4. the tree may has more than one branch.
5.Guaranteed constraints:
flattree.length = n - 1,
flattree[i].length = 2,
0 ≤ flattree[i][j] < n.
6. the return is the max the diameter of the tree. It is the longest path in the two any vertex.
////////////////////

#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> adj;

pair<int, int> dfs(int node, int parent) {
    pair<int, int> res = {0, node};
    for (int child : adj[node]) {
        if (child != parent) {
            pair<int, int> child_res = dfs(child, node);
            res = max(res, {child_res.first + 1, child_res.second});
        }
    }
    return res;
}

int solution(int n, vector<vector<int>> flattree) {
    adj = vector<vector<int>>(n);
    for (const auto &edge : flattree) {
        adj[edge[0]].push_back(edge[1]);
        adj[edge[1]].push_back(edge[0]);
    }
    pair<int, int> p = dfs(0, -1);
    pair<int, int> q = dfs(p.second, -1);
    return q.first;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值