Count the Number of Good Nodes - Post-Order DFS [JS]

Description 

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]