All problems

Problem 618

Count Nodes Equal to Average of Subtree

Medium · 20 pts · Tree, Depth-First Search

Problem

For every node, consider its subtree: the node itself and all its descendants. The average of the subtree is the sum of its values divided by the number of its nodes, rounded down to an integer. Count the nodes whose value equals the average of their own subtree. A post-order search returns the (sum, count) of each subtree, so every node is checked in O(1) and the whole tree in O(N).

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print the number of nodes equal to the average of their subtree.

Constraints

1 <= number of nodes <= 1000; 0 <= value <= 1000

Example input

7
4 8 5 0 1 null 6

Example output

5

Explanation

In the tree 4 8 5 0 1 null 6, the root's subtree averages floor(24 / 6) = 4, the node 5 averages floor(11 / 2) = 5, and the leaves 0, 1 and 6 each equal their own average. Node 8 averages 3, so the answer is 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Smallest String Starting From Leaf Next: Maximum Sum BST in Binary Tree