Problem 613
Count Univalue Subtrees
Medium · 20 pts · Tree, Depth-First Search
Problem
A univalue subtree is a subtree in which all nodes have the same value. Every node defines one subtree (the node with all its descendants), and every leaf is a univalue subtree on its own. Count the univalue subtrees of the given tree. A post-order search can report for each subtree whether it is univalue: a node's subtree is univalue when both child subtrees are univalue and each existing child has the node's value.
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 univalue subtrees.
Constraints
1 <= number of nodes <= 10000; -1000 <= value <= 1000
Example input
7 5 1 5 5 5 null 5
Example output
4
Explanation
In the tree 5 1 5 5 5 null 5, the three leaves (all with value 5) are univalue subtrees, and so is the right child 5 together with its child 5. The subtrees of 1 and of the root mix values, so the answer is 4.