# Question

Formatted question description: https://leetcode.ca/all/965.html

A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

Example 1:



Input: [1,1,1,1,1,null,1]
Output: true
Example 2:



Input: [2,2,2,5,2]
Output: false

Note:

The number of nodes in the given tree will be in the range [1, 100].
Each node's value will be an integer in the range [0, 99].



# Algorithm 1

This question defines a single-valued binary tree that requires all nodes in the binary tree to have the same value. First, I gave a binary tree and asked if it was a single-value binary tree. In fact, it is to investigate and traverse the binary tree, of course, the recursive method is the simplest in writing. Here, each node value can be compared with the root node value, as long as any one is different, it means that it is not a single-valued binary tree. Therefore, it is necessary to substitute the root node value as a parameter into the recursive function, so write a helper function to perform recursive writing of pre-order traversal, see the code as follows:

C++

# Algorithm 2

In a function comparison, as long as the values of the left and right child nodes of any node (if stored) are equal to the value of its parent node, it must be a single-valued binary tree. So in a function can also be compared, see the code as follows:

C++

Java

# Algorithm 3

The above solutions are all recursive. Let’s look at the layer order traversal of iterative writing. There is no difference in the way of solving the problem, just the method of traversal is different. See the code as follows:

C++