Java | DFS | Parent Graph | TreeSet | Easy to Understand
Solution:\n\nclass Solution {\n    public List<List<Integer>> getAncestors(int n, int[][] edges) {\n        List<Integer>[] parents = new ArrayList[n];\n       
**Solution:**\n```\nclass Solution {\n    public List<List<Integer>> getAncestors(int n, int[][] edges) {\n        List<Integer>[] parents = new ArrayList[n];\n        TreeSet<Integer>[] ancestors = new TreeSet[n];\n        for (int i = 0; i < n; ++ i) {\n            parents[i] = new ArrayList<>();\n        }\n        \n        for (int[] edge: edges) {\n            parents[edge[1]].add(edge[0]);\n        }\n        \n        List<List<Integer>> result = new ArrayList<>();\n        for (int i = 0; i < n; ++ i) {\n            if (ancestors[i] == null) {\n                dfs(i, parents, ancestors);\n            }\n            \n            result.add(new ArrayList<>(ancestors[i]));\n        }\n        \n        return result;\n    }\n    \n    public void dfs(int node, List<Integer>[] parents, TreeSet<Integer>[] ancestors) {\n        TreeSet<Integer> set = new TreeSet<>();\n        for (int parent: parents[node]) {\n            set.add(parent);\n            if (ancestors[parent] == null) {\n                dfs(parent, parents, ancestors);\n            }\n            set.addAll(ancestors[parent]);\n        }\n        \n        ancestors[node] = set;\n    }\n}\n```\n
['Depth-First Search', 'Java']