Niuke.net brushing questions-the diameter of the tree

Problem Description

Given a tree, find the diameter of the tree, that is, the distance between the two furthest points on the tree.

Input description: the
number of input nodes, the two nodes of each edge, the weight of the edge

Output description:
output the longest path

Example

Example 1

Enter
6,[[0,1],[1,5],[1,2],[2,3],[2,4]],[3,4,2,1,5]

Output
11

Solutions

analysis

This question is mainly through depth-first traversal, and the maximum value is obtained by comparing and judging the weight value of each path.

method

  1. Using depth-first traversal, traverse the tree to get the maximum value

Code

public class Solution {
    
    
    /**
     * 树的直径
     *
     * @param n int整型 树的节点个数
     * @param Tree_edge Interval类一维数组 树的边
     * @param Edge_value int整型一维数组 边的权值
     * @return int整型
     */
    //6,[[0,1],[1,5],[1,2],[2,3],[2,4]],[3,4,2,1,5]
    int res = 0;

    public int solve(int n, Interval[] Tree_edge, int[] Edge_value) {
    
    
        // write code here
        // list数组存储每个节点的所有边
        List<int[]>[] map = new ArrayList[n];
        // 将所有的节点初始化
        for (int i = 0; i < n; i++) map[i] = new ArrayList();
        // 遍历所有的边,一次添加到对应数组的list中
        for (int i = 0; i < Tree_edge.length; i++) {
    
    
            // 起始节点的边,存储终节点和边的权重值
            map[Tree_edge[i].start].add(new int[]{
    
    Tree_edge[i].end, Edge_value[i]});
            // 终节点的边,存储起节点和权重值
            map[Tree_edge[i].end].add(new int[]{
    
    Tree_edge[i].start, Edge_value[i]});
        }
        // 深度优先遍历,通过数组的bool值判断节点是否已经访问过
        dfs(map, 0, new boolean[n]);
        return res;
    }

    private int dfs(List<int[]>[] map, int index, boolean[] visited) {
    
    
        // 将节点置为已经访问
        visited[index] = true;
        // 获取节点的所有的边
        List<int[]> list = map[index];
        int weight1 = 0, weight2 = 0;
        // 遍历所有的边
        for (int[] child2weight : list) {
    
    
            // 获取边的另一端
            int child = child2weight[0];
            // 获取边的权重
            int weight = child2weight[1];
            // 判断边是否已经访问
            if (visited[child]) continue;
            // 计算路径长度
            int num = weight + dfs(map, child, visited);

            if (num > weight1) {
    
    
                weight2 = weight1;
                weight1 = num;
            } else if (num > weight2) {
    
    
                weight2 = num;
            }
            if (weight1 + weight2 > res) res = weight1 + weight2;
        }
        return Math.max(weight1, weight2);
    }
}

If you want to test, you can go directly to the link of Niuke.com to do the test

The diameter of the tree

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/112690076