public static int CountUnivalSubtrees(Node node)
{
if (node == null)
return 0;
int count = CountUnivalSubtrees(node.left);
count += CountUnivalSubtrees(node.right);
return IsUnivalTree(node) ? count + 1 : count;
}
private static bool IsUnivalTree(Node node)
{
if (node == null)
return true;
if (node.left != null && node.left.val != node.val)
return false;
if (node.right != null && node.right.val != node.val)
return false;
return IsUnivalTree(node.left) && IsUnivalTree(node.right);
}