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 input

Input: 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}

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int balancedSubtrees(int n, vector<int>& a, string s) {
// Write your code here
return 0;
}
};
Test Case

Input:

A
N
S