To find the center of a tree represented by edges, we need to identify the node that has a degree (number of connected edges) equal to n-1
, where n
is the number of nodes in the tree. In a tree with n
nodes, all nodes except the center will have a degree of exactly 1, and the center will have a degree of n-1
.
- Initialize: Determine the number of nodes
n
in the tree, which islen(edges) + 1
because there arelen(edges)
edges connectinglen(edges) + 1
nodes. - Degree Counting: Create an array
degreeCount
of sizen+1
to store the degree of each node. Traverse through each edge and increment the degree count for both nodes involved in the edge. - Find the Center: Traverse through the
degreeCount
array from 1 ton
. The first node that has a degree equal ton-1
is the center of the tree.
- Time complexity: O(n), where
n
is the number of nodes in the tree. We iterate through the edges to compute degrees (O(e)
, wheree
is the number of edges) and then iterate through the nodes (O(n)
) to find the center. - Space complexity: O(n). We use additional space for the
degreeCount
array, which hasn+1
elements. Thus, the space complexity is linear in terms of the number of nodes.