Skip to content

Practice Count the Number of Good Nodes

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#3249
LeetCode Problem

Count the Number of Good Nodes

Problem Statement

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] = [ai, bi] indicates that there is an edge between nodes ai and bi 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.

Source: Count the Number of Good Nodes on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output
7

# Example 2

Input
edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]
Output
6

# Example 3

Input
edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]
Output
12

Constraints

2 <= n <= 10^5
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
The input is generated such that edges represents a valid tree.

Related LeetCode Problems

Practice more problems similar to Count the Number of Good Nodes.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.