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.
Example 1:
Input: root = [1,1,1,1,1,null,1] Output: true
Example 2:
Input: root = [2,2,2,5,2] Output: false
Constraints:
[1, 100]
.0 <= Node.val < 100
class Solution {
public boolean helper(TreeNode root , int val){
if(root == null){
return true ;
}
if(root.val != val){
return false ;
}
boolean leftans = helper(root.left,val);
boolean rightans = helper(root.right,val);
return leftans && rightans;
}
public boolean isUnivalTree(TreeNode root) {
return helper(root,root.val);
}
}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India