Count the Number of Good Nodes - Post-Order DFS [JS]
Solution: Post-Order DFS
Post-order DFS to get the size of each child subtree.
Use a hashset to keep track of how many different subtree sizes there are, if the hashset has more than one element, then the tree is not good.
Time Complexity: O(n)
Space Complexity: O(n)
function countGoodNodes(edges) {
let n = edges.length + 1;
let graph = Array(n).fill(0).map(() => []);
for (let [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
let good = 0;
dfs(0, -1);
return good;
function dfs(node, parent) {
let sizes = new Set(), size = 1;
for (let nei of graph[node]) {
if (nei === parent) continue;
let neiSize = dfs(nei, node);
sizes.add(neiSize);
size += neiSize;
}
if (sizes.size <= 1) good++;
return size;
}
};
Comments
Post a Comment