363. Count Univalue Subtrees
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5]
Output: 4
Explanation:
We traverse the tree and count the number of subtrees where all nodes have the same value.
The leaf nodes (5, 5, and 5) are uni-value subtrees.
The left subtree with root 1 is not a uni-value subtree since it has different values.
The right subtree rooted at 5 (with only one child 5) is a uni-value subtree.
The entire right subtree (excluding the root) is also a uni-value subtree.
Total count = 4.
Example 2:
Input: root = [5,5,5,5,5,null,5]
Output: 6
Explanation:
Each leaf node (5) is a uni-value subtree.
The left and right subtrees rooted at 5 (excluding the main root) are also uni-value subtrees.
The entire left subtree and right subtree of the root are uni-value subtrees.
The entire tree is a uni-value subtree.
Total count = 6.
Now Your Turn!
Pick the correct output for the given inputInput: root = [1,1,2,5,1,null,5]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- The number of the node in the tree will be in the range [0, 1000].
- -1000 <= Node.val <= 1000