Count Univalue Subtrees
Description
null
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const countUnivalSubtrees = function (root) {
const aux = (node) => {
if (!node) {
return [true, null, 0]
}
const [leftValid, leftVal, count1] = aux(node.left)
const [rightValid, rightVal, count2] = aux(node.right)
const { val } = node
const count = count1 + count2
if (leftValid && rightValid) {
if (leftVal === null && rightVal === null) {
return [true, val, count + 1]
}
if (leftVal === null || rightVal === null) {
if (val === (leftVal === null ? rightVal : leftVal)) {
return [true, val, count + 1]
}
return [false, val, count]
}
if (leftVal === val && rightVal === val) {
return [true, val, count + 1]
}
return [false, val, count]
}
return [false, val, count]
}
return aux(root)[2]
}