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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code