Count Univalue Subtrees Problem
Description
LeetCode Problem 250.
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
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [5,5,5,5,5,null,5]
Output: 6
Constraints:
- The number of the node in the tree will be in the range
[0, 1000]. -1000 <= Node.val <= 1000
Solution
Approach: Post-Order DFS
Whether a subtree is uni-value depends on its children: a node's subtree is uni-value when
- the left subtree is uni-value (or empty) and its root has the node's value, and
- the same holds for the right subtree.
So we work bottom-up. A helper returns whether the subtree under a node is uni-value, and adds one to a counter each time it is. An empty tree counts as uni-value, so leaves pass both checks and are always counted.
The helper must visit both children before it decides anything. If it returned false as soon as the left side failed, it would never look at the right subtree, and the uni-value subtrees inside it would not be counted. That is why the code calls the helper on both children first and only then compares values.
Complexity: O(n) time, since each node is visited once, and O(h) space for the recursion, where h is the height of the tree.
class Solution:
def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
count = 0
def is_unival(node):
"""Whether every node under node has node's value (an empty tree counts)."""
nonlocal count
if node is None:
return True
# Visit both children first: their subtrees must be counted even if this one fails.
left, right = is_unival(node.left), is_unival(node.right)
if not left or not right:
return False
if node.left and node.left.val != node.val:
return False
if node.right and node.right.val != node.val:
return False
count += 1
return True
is_unival(root)
return count