A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Input: root = [1,1,1,1,1,null,1]
Output: true
Recursive:
- all nodes must be the same value, use helper to maintain
Time: O(n)
Space: O(n)
Recursive
public boolean isUnivalTree(TreeNode root) {
return helper(root, root.val);
}
private boolean helper(TreeNode root, int val) {
if (root == null)
return true;
return root.val == val && helper(root.left, val) && helper(root.right, val);
}