714阿里巴巴模拟面试

介绍一下数据库分页

https://www.nowcoder.com/questionTerminal/3577280c810546658f06f19c01ff0345

给定一棵树,求出这棵树的直径,即两个节点距离的最大值。

应该是左右子树遍历深度之和,广度优先搜索+深度优先搜索
注意输入输出。。。。。

public class Solution {
    /**
     * 树的直径
     * @param n int整型 树的节点个数
     * @param Tree_edge Interval类一维数组 树的边
     * @param Edge_value int整型一维数组 边的权值
     * @return int整型
     */
    public int solve (int n, Interval[] Tree_edge, int[] Edge_value) {
        // write code here
        if(Tree_edge == null || Edge_value == null || Tree_edge.length != Edge_value.length){return 0;}
        Map<Integer, List<Edge>> graph = new HashMap<>();
        int len = Tree_edge.length;
        for(int i = 0; i < len; ++i){
            Interval inter = Tree_edge[i];
            int start = inter.start;
            int end = inter.end;
            int w = Edge_value[i];
            Edge e1 = new Edge(end, w);
            if(!graph.containsKey(start)){
                List<Edge> temp = new ArrayList<>();
                graph.put(start, temp);
            }
            graph.get(start).add(e1);
            Edge e2 = new Edge(start, w);
            if(!graph.containsKey(end)){
                List<Edge> temp = new ArrayList<>();
                graph.put(end, temp);
            }
            graph.get(end).add(e2);
        }
        int[] remote = {0, 0};    // remote[0] 代表以0为起点的最长路径长度, remote[1]代表最长路径的终点
        dfs(graph, 0, -1, 0, remote);
        int[] res = {0, 0};
        dfs(graph, remote[1], -1, 0, res);
        return res[0];
    }
    
    private class Edge{
        int end;
        int w;
        Edge(int end, int w){
            this.end = end;
            this.w = w;
        }
    }
    
    private void dfs(Map<Integer, List<Edge>> graph, int from, int prev, int path, int[] res){
        List<Edge> edges = graph.get(from);
        for(Edge edge: edges){
            if(edge.end != prev){
                path += edge.w;
                if(path > res[0]){
                    res[0] = path;
                    res[1] = edge.end;
                }
                dfs(graph, edge.end, from, path, res);
                path -= edge.w;    // 回溯
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值