check if every value on this tree is univalue or not.
using recursion and the equation will be:
isUnivalue(root) = isUnivalue(root.left) && isUnivalue(root.right)
but the problem is we don’t have the value to compare if any one is false.
so I use an extra recursion.
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) return true;
//if root is not null, then it means each value should have the same value as rppt.val
return isUnivalTree(root, root.val);
}
private boolean isUnivalTree(TreeNode root, int value) {
if (root == null) return true;
if (root.val != value) return false;
return isUnivalTree(root.left, value) && isUnivalTree(root.right, value);
}
}