2192. 有向无环图中一个节点的所有祖先

1、题目描述:

https://leetcode-cn.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/

2、思路:

  遍历一遍二维数组,可以统计出所有节点的父节点;因此要想知道一个节点的所有祖宗节点,就再拿到父节点,去找父节点的父节点,递归的过程。

3、代码:

class Solution {
    public List<List<Integer>> getAncestors(int n, int[][] edges) {
        ArrayList<List<Integer>> list = new ArrayList<>(), result = new ArrayList<>();
        TreeSet<Integer>[] sets = new TreeSet[n];
        for (int i = 0; i < n; i++) {
            list.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            //遍历edges数组,对于每个被指向的节点,存储指向其的节点即父亲节点
            list.get(edge[1]).add(edge[0]);
        }
        for (int i = 0; i < n; i++) {
            result.add(List.copyOf(getAncestors(i, list, sets)));
        }
        return result;
    }

    private TreeSet<Integer> getAncestors(int index, ArrayList<List<Integer>> list, TreeSet<Integer>[] sets) {
        // sets数组存储每个节点的所有祖宗节点 list存储每个节点的所有父亲节点
        // 当其祖宗节点为空时,遍历所有父亲节点,添加父亲节点,递归查找父亲节点的父亲节点并添加
        // 当祖宗节点不为空时,说明这个节点已经被处理过,此时被调用说明来自于其孩子节点的祖宗查询,直接返回其所有祖宗节点即可
        if (sets[index] == null) {
            sets[index] = new TreeSet<>();
            for (int i : list.get(index)) {
                sets[index].add(i);
                sets[index].addAll(getAncestors(i, list, sets));
            }
        }
        return sets[index];
    }
}

 

。。

posted @ 2022-04-05 13:00  guoyu1  阅读(118)  评论(0编辑  收藏  举报