Similar to binary tree find longest path problem on leetcode, but since we are dealing with n-ary tree with alternating tags, some modifications are needed.
int ans;
List<Integer>[] adjList;
String values;
public int longestAlternatingPath(int[] parent, String tag) {
int n = parent.length;
adjList = new List[n];
ans = 0;
values = tag;
for(int i=1; i<n; i++) {
if(adjList[parent[i]]==null) adjList[parent[i]] = new ArrayList<>();
adjList[parent[i]].add(i);
}
dfs(0);
return ans;
}
private int[] dfs(int node) {
PriorityQueue<Integer> top2a = new PriorityQueue<>(), top2b = new PriorityQueue<>();
if(adjList[node]!=null) {
for(int child : adjList[node]) {
int[] counts = dfs(child);
top2a.offer(counts[0]);
if(top2a.size()>2) top2a.poll();
top2b.offer(counts[1]);
if(top2b.size()>2) top2b.poll();
}
}
int a2 = top2a.isEmpty()? 0 : top2a.poll(), a1 = top2a.isEmpty()? 0 : top2a.poll();
int b2 = top2b.isEmpty()? 0 : top2b.poll(), b1 = top2b.isEmpty()? 0 : top2b.poll();
int count = values.charAt(node)=='a'? (b1+b2+1) : (a1+a2+1);
ans = Math.max(ans, count);
return values.charAt(node)=='a'? new int[]{b1+1, 0} : new int[]{0, a1+1};
}