Count the Number of Good Nodes - Problem

Imagine a family tree where node 0 is the patriarch/matriarch at the root. Each node represents a family member, and the connections show parent-child relationships. Given an undirected tree with n nodes labeled from 0 to n-1, you need to determine how many nodes are "good".

A node is considered good if all of its children's subtree sizes are identical. In other words, if you look at any node and count how many descendants each of its children has (including the child itself), those counts must all be equal for the node to be "good".

Input: A 2D array edges where edges[i] = [a_i, b_i] represents an edge between nodes a_i and b_i.

Output: Return the total count of good nodes in the tree.

Note: Leaf nodes (nodes with no children) are always considered good since there are no subtrees to compare!

Input & Output

example_1.py โ€” Basic Tree
$ Input: edges = [[0,1],[0,2],[1,3],[1,4]]
โ€บ Output: 4
๐Ÿ’ก Note: Tree structure: 0->1,2 where 1->3,4. Node 0 is not good (children have subtree sizes 3 and 1). Node 1 is good (children 3,4 both have subtree size 1). Nodes 2,3,4 are good (leaves). Total: 4 good nodes.
example_2.py โ€” Single Node
$ Input: edges = []
โ€บ Output: 1
๐Ÿ’ก Note: Single node tree with just node 0. A single node has no children, so it's considered good by definition.
example_3.py โ€” Balanced Tree
$ Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
โ€บ Output: 6
๐Ÿ’ก Note: Perfect binary tree where node 0 has children 1,2, each with subtree size 3. Node 1 has children 3,4 (size 1 each). Node 2 has children 5,6 (size 1 each). All nodes are good since children have equal subtree sizes. Total: 6 good nodes.

Constraints

  • 1 โ‰ค n โ‰ค 105 where n is the number of nodes
  • edges.length == n - 1 (valid tree structure)
  • 0 โ‰ค ai, bi < n
  • The given edges form a valid tree (connected and acyclic)

Visualization

Tap to expand
CEO (0)Team: 5VP1 (1)Team: 3VP2 (2)Team: 1Mgr (3)Mgr (4)โœ“โœ“โœ“โœ“โœ—Balance Analysis:โœ“ Managers 3,4: Balanced (no direct reports)โœ“ VP1: Balanced (reports manage teams of size 1,1)โœ“ VP2: Balanced (leaf node)โœ— CEO: Not balanced (reports manage teams of size 3,1)
Understanding the Visualization
1
Start from Leaves
Begin with employees who manage no one - they're automatically balanced
2
Calculate Team Sizes
For each manager, sum up team sizes of direct reports
3
Check Balance
Compare if all direct reports have equal team sizes
4
Propagate Upward
Move up the hierarchy using calculated team sizes
Key Takeaway
๐ŸŽฏ Key Insight: Post-order DFS ensures we calculate team sizes from bottom-up, allowing us to check balance conditions efficiently in O(n) time.
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
41.3K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen