Similar questions:
Time = O(n), space = O(h)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int count = 0;
public int countUnivalSubtrees(TreeNode root) {
helper(root);
return count;
}
private boolean helper(TreeNode root) {
if (root == null) {
return true;
}
boolean curUni = true;
boolean left = helper(root.left);
boolean right = helper(root.right);
if (root.left != null) {
curUni = curUni && left && (root.left.val == root.val);
}
if (root.right != null) {
curUni = curUni && right && (root.right.val == root.val);
}
if (curUni) {
count += 1;
}
return curUni;
}
}