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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isUnivalTree = function(root) {
const value = root.val;
return checkIfUnivalued(root, value);
};
const checkIfUnivalued = (root, value) => {
if (root === null) {
return true;
}
if (root && root.val !== value) {
return false;
}
return (
checkIfUnivalued(root.left, value) && checkIfUnivalued(root.right, value)
);
};
Top comments (0)