[Java] Small-To-Large Merging
\nclass Solution {\n    public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n        List<Integer>[] children = new ArrayList[parents.length];
```\nclass Solution {\n    public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n        List<Integer>[] children = new ArrayList[parents.length];\n        for (int i = 0; i < parents.length; i++) {\n            children[i] = new ArrayList<>();\n        }\n        for (int i = 1; i < parents.length; i++) {\n            children[parents[i]].add(i);\n        }\n        int[] depth = new int[parents.length];\n        Queue<Integer> q = new LinkedList<>();\n        q.offer(0);\n        while (!q.isEmpty()) {\n            int current = q.poll();\n            for (int i : children[current]) {\n                depth[i] = depth[current] + 1;\n                q.offer(i);\n            }\n        }\n        List<Integer> sort = new ArrayList<>();\n        for (int i = 0; i < parents.length; i++) {\n            sort.add(i);\n        }\n        Collections.sort(sort, (a, b) -> depth[b] - depth[a]);\n        HashSet<Integer>[] set = new HashSet[parents.length];\n        int[] size = new int[parents.length], first = new int[parents.length];\n        Arrays.fill(first, 1);\n        for (int i : sort) {\n            for (int j : children[i]) {\n                size[i] += size[j];\n                first[i] = Math.max(first[i], first[j]);\n            }\n            size[i]++;\n            if (children[i].isEmpty()) {\n                set[i] = new HashSet<>();\n            } else {\n                int max = 0;\n                for (int j = 1; j < children[i].size(); j++) {\n                    if (size[children[i].get(j)] > size[children[i].get(max)]) {\n                        max = j;\n                    }\n                }\n                set[i] = set[children[i].get(max)];\n                for (int j = 0; j < children[i].size(); j++) {\n                    if (j != max) {\n                        for (int k : set[children[i].get(j)]) {\n                            set[i].add(k);\n                        }\n                    }\n                }\n            }\n            set[i].add(nums[i]);\n            while (set[i].contains(first[i])) {\n                first[i]++;\n            }\n        }\n        return first;\n    }\n}\n```
[]