Problem 603
Univalued Binary Tree
Easy · 10 pts · Tree, Depth-First Search
Problem
A binary tree is univalued if every node in it has the same value. Decide whether the given tree is univalued. A tree with a single node is always univalued. Visit all the nodes with a depth-first or breadth-first search and compare each value with the root's value; you can stop as soon as one differs.
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 YES if the tree is univalued, otherwise NO.
Constraints
1 <= number of nodes <= 100; 0 <= value <= 100
Example input
7 1 1 1 1 1 null 1
Example output
YES
Explanation
In the tree 1 1 1 1 1 null 1, all six nodes have the value 1, so the tree is univalued and the answer is YES.