Same idea.

class Solution { int count = 0; public int countUnivalSubtrees(TreeNode root) { if (root == null) { return 0; } traverseSubtree(root); return count; } public boolean traverseSubtree(TreeNode root) { if (root.left == null && root.right == null) { count++; return true; } boolean left = root.left == null? true : traverseSubtree(root.left); boolean right = root.right == null? true : traverseSubtree(root.right); int leftValue = root.left == null? root.val: root.left.val; int rightValue = root.right == null? root.val: root.right.val; if (left && right && leftValue == root.val && rightValue == root.val) { count++; return true; } return false; } }Count Univalue Subtrees