My Python solution is following:

```
class Solution:
# @param {TreeNode} root
# @return {integer}
def countUnivalSubtrees(self, root):
if not root: return 0
if (not root.left) and (not root.right): return 1
if not root.left: return self.countUnivalSubtrees(root.right) + int(root.right.val == root.val)
if not root.right: return self.countUnivalSubtrees(root.left) + int(root.left.val == root.val)
return int(root.val == root.left.val == root.right.val) + self.countUnivalSubtrees(root.left) + self.countUnivalSubtrees(root.right)
```

It passed almost all test cases but failed in certain cases. Who can tell what the problem is ?