为了能到远方|

fishcanfly

园龄:8年9个月粉丝:0关注:4

[1483. 树节点的第 K 个祖先] 【路径】

思路很简单:


import java.util.ArrayList;
import java.util.List;

class TreeAncestor {
    List<Integer>[] children;
    List<List<Integer>> paths = new ArrayList<>();
    int[][] pathIdMap;

    public static void main(String[] args) {
        TreeAncestor ancestor = new TreeAncestor(5, new int[]{
                -1, 0, 0, 0, 3
        });
        int ans = ancestor.getKthAncestor(3, 2);
        System.out.println(ans);
    }

    public TreeAncestor(int n, int[] parent) {
        children = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            children[i] = new ArrayList<>();
        }
        for (int i = 0; i < n; i++) {
            if (i == 0) {
                continue;
            }
            children[parent[i]].add(i);
        }

        int pathId = 0;
        pathIdMap = new int[n + 1][2];
        for (int i = 0; i < n; i++) {
            if (!children[i].isEmpty()) {
                continue;
            }
            List<Integer> path = new ArrayList<>();
            int val = i;
            int num = 0;
            while (val != -1) {
                path.add(val);
                pathIdMap[val][0] = pathId;
                pathIdMap[val][1] = num++;
                val = parent[val];
            }
            paths.add(path);
            pathId++;
        }
    }

    public int getKthAncestor(int node, int k) {
        int[] pathId = pathIdMap[node];
        List<Integer> path = paths.get(pathId[0]);
        int size = path.size();
        int offset = pathId[1];
        if (size <= offset + k) {
            return -1;
        }
        return path.get(offset + k);
    }
}

/**
 * Your TreeAncestor object will be instantiated and called as such:
 * TreeAncestor obj = new TreeAncestor(n, parent);
 * int param_1 = obj.getKthAncestor(node,k);
 */

本文作者:love

本文链接:https://www.cnblogs.com/fishcanfly/p/18117748

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   fishcanfly  阅读(5)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起