树的直径——后序遍历(java)

树的直径

http://www.nowcoder.com/questionTerminal/a77b4f3d84bf4a7891519ffee9376df3

import java.util.*;
public class Solution {
   class Node{  // 邻接点结构
        int id, dist; //id表示节点编号,dist表示距离
        public Node(){}
        public Node(int id, int dist){
            this.id = id;
            this.dist = dist;
        }
    }
    int maxv = 0;
    List<Node>[] g; // 保存邻接点

    public int solve (int n, Interval[] Tree_edge, int[] Edge_value) {
        g = new List[n];
        for (int i = 0; i < n; ++i){
            g[i] = new LinkedList<>();
        }

        for (int i = 0; i < n - 1; ++i){
            int x = Tree_edge[i].start, y = Tree_edge[i].end;
            g[x].add(new Node(y, Edge_value[i]));
            g[y].add(new Node(x, Edge_value[i]));

        }
        dfs(0, -1);
        return maxv;
    }
    public int dfs(int root, int parent){
        List<Integer> list  = new LinkedList<>();
        for (Node v : g[root]){
            if (v.id == parent) continue;
            list.add(dfs(v.id, root) + v.dist);
        }
        Collections.sort(list);
        int n = list.size(), val = 0;
        for (int i = n - 1; i >= 0 && i >= n - 2; --i){
            val += list.get(i);
        }
        maxv = Math.max(maxv, val);
        return n == 0 ? 0 : list.get(n - 1);
    }
}






全部评论

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
3 收藏 评论
分享
牛客网
牛客企业服务