250. Count Univalue Subtrees
Leetcode
題目
Input: root = [5,1,5,5,5,null,5]
Output: 4Input: root = []
Output: 0Input: root = [5,5,5,5,5,null,5]
Output: 6解答
Last updated
Input: root = [5,1,5,5,5,null,5]
Output: 4Input: root = []
Output: 0Input: root = [5,5,5,5,5,null,5]
Output: 6Last updated
var countUnivalSubtrees = function(root) {
let count = 0;
const helper = (node) => {
if (!node) return [true];
const val = node.val;
if (!node.left && !node.right) {
count++;
return [true, val]
}
// node.left 是 null 的話,預設帶 leftValue 等於本身的 val
const [isLeftUnival, leftValue = val] = helper(node.left);
const [isRightUnival, rightValue = val] = helper(node.right);
const isValueSame = val === leftValue && val === rightValue;
const isUniVal = isLeftUnival && isRightUnival && isValueSame;
if (isUniVal) count++;
return [isUniVal, val]
}
helper(root);
return count;
};var countUnivalSubtrees = function(root) {
let count = 0;
const isUnival = (node, parentVal) => {
if (!node) return true;
const nodeVal = node.val;
const conditions = [isUnival(node.left, nodeVal), isUnival(node.right, nodeVal)];
// 使用 every 確保左右的節點都跑完 isUnival function
if (!conditions.every(condition => condition)) {
return false;
}
// 左右節點都是 isUnival 的話就可以 count+1 了
count++;
return nodeVal === parentVal;
}
// 初始值帶入超過上限 1000 的 parentVal
isUnival(root, 1001);
return count;
};