Count the Number of Good Nodes - Problem

There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are given a 2D integer array edges of length n - 1, where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i in the tree.

A node is good if all the subtrees rooted at its children have the same size. Return the number of good nodes in the given tree.

A subtree of treeName is a tree consisting of a node in treeName and all of its descendants.

Input & Output

Example 1 — Balanced Tree
$ Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output: 7
💡 Note: Tree rooted at 0 with balanced subtrees. Node 0 has children 1,2 with subtree sizes 3,3 (equal). Node 1 has children 3,4 with sizes 1,1. Node 2 has children 5,6 with sizes 1,1. All leaf nodes (3,4,5,6) have no children. All 7 nodes are good.
Example 2 — Unbalanced Tree
$ Input: edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 5
💡 Note: Linear tree: 0-1-2-3-4. Each node has at most one child, so all nodes are good (single child always has 'equal' sizes with itself). Total: 5 good nodes.
Example 3 — Single Node
$ Input: edges = []
Output: 1
💡 Note: Tree with only node 0. Since it has no children, it's considered good. Total: 1 good node.

Constraints

  • 1 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • The input represents a valid tree

Visualization

Tap to expand
Count Good Nodes: Tree with Equal Subtree SizesInput: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]0123456Node 0: ✓ GoodChildren 1,2 have sizes 3,3Node 1: ✓ GoodChildren 3,4 have sizes 1,1Node 2: ✓ GoodChildren 5,6 have sizes 1,1Leaves 3,4,5,6: ✓ GoodNo children (vacuously true)Output: 7 (All nodes are good)A node is good if all its children have equal subtree sizes
Understanding the Visualization
1
Input Tree
Undirected tree with edges defining parent-child relationships
2
Check Each Node
For each node, compare subtree sizes of all children
3
Count Good Nodes
Nodes with equal child subtree sizes are 'good'
Key Takeaway
🎯 Key Insight: Use DFS to calculate subtree sizes once and check equality of children's sizes
Asked in
Google 25 Meta 18 Amazon 15
12.5K Views
Medium Frequency
~25 min Avg. Time
342 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