DeloitteOA #2
Count Balanced Nodes in a Tree
Estimated MediumJudge-ready
Topics (AI-labelled)Tree Traversal
You are given a tree rooted at node 1. A node is balanced if the subtrees of all its direct children have the same size; leaf nodes are considered balanced as stated in the problem. Output the total number of balanced nodes. This site supplements the parent-list input protocol and the size limits.
Input
The first line contains n (1≤n≤200000); the second line contains n−1 integers, the parent labels of nodes 2..n in order (1-based). When n=1, the second line may be empty. The input is guaranteed to form a tree rooted at node 1.
Output
Output the number of balanced nodes.
Example 1
Input:
1
Output:
1
Example 2
Input:
4
1 2 3
Output:
4
Example 3
Input:
4
1 1 2
Output:
3
Editorial
Loading solution…