White-Black Balanced Subtrees
You are given a rooted tree with n nodes. The root is node 1.
Each node has a color: B ā black W ā white
Array `a`: An integer array of length n - 1 representing the tree structure. For any 0-based index i, a[i] is the parent of node i + 2. (For example, a[0] is the parent of node 2, a[1] is the parent of node 3, etc.)
String `s`: A string of length n consisting only of characters 'W' and 'B'. For any 0-based index i, s.charAt(i) represents the color of node i + 1. (For example, s[0] is the color of node 1).
A subtree is called balanced if: number of white nodes = number of black nodes
Your task is to Count how many subtrees are balanced
Example 1:
Input: n = 5, a = [1, 1, 2, 3], s = 'WBBWW'
Output :2
Explanation:
Tree:
1(W) āā2(B) ā āā4(W) āā3(B) āā5(W)
Subtrees:
node1 ā W B B W W ā white=3 black=2 ā not balanced node2 ā B W ā balanced node3 ā B W ā balanced node4 ā W ā not node5 ā W ā not
Balanced subtrees: 2
Example 2:
Input : n= 3, a = [1, 1], s = 'BWB'
Output: 0
Explanation:
subtree1 ā B W B ā white=1 black=2 subtree2 ā W subtree3 ā B
None balanced.
Now Your Turn!
Pick the correct output for the given inputInput: n = 2, a = [1], s = 'BW'
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ⤠n ⤠2 * 105
- colors ā {B, W}