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 the Number of Good Nodes INPUT Tree Structure (rooted at 0) 0 1 2 3 4 5 6 edges array: [[0,1], [0,2], [1,3], [1,4], [2,5], [2,6]] n = 7 nodes rooted at node 0 ALGORITHM STEPS (Optimized DFS) 1 Build Adjacency List Convert edges to graph 2 DFS from Root Traverse tree post-order 3 Calculate Subtree Size Sum of children sizes + 1 4 Check Good Node All children same size? Subtree Sizes: 0 size=7 1 size=3 2 size=3 3,4: size=1 5,6: size=1 Children of 0: both size 3 - OK FINAL RESULT Good Nodes Analysis 0 OK 1 OK 2 OK 3 OK 4 OK 5 OK 6 OK Node 0: children 1,2 both size 3 Node 1: children 3,4 both size 1 Node 2: children 5,6 both size 1 Leaves 3,4,5,6: no children = OK Output: 7 Key Insight: A node is "good" if ALL its children's subtrees have the SAME size. Leaf nodes (no children) are always good. Use post-order DFS to calculate subtree sizes bottom-up, then check if all child subtree sizes are equal. Time Complexity: O(n) | Space Complexity: O(n) for adjacency list and recursion stack. TutorialsPoint - Count the Number of Good Nodes | Optimized DFS Approach
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