VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-node-at-the-centre-of-an-n-ary-tree/

⇱ Find the node at the center of an N-ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the node at the center of an N-ary tree

Last Updated : 15 Jul, 2025

Prerequisites: 

Given a N-ary tree with N nodes numbered from 0 to N-1 and a list of undirected edges, the task is to find the node(s) at the center of the given tree.

Eccentricity: The eccentricity of any vertex V in a given tree is the maximum distance between the given vertex V and any other vertex of the tree. 
Center: The center of a tree is the vertex having the minimum eccentricity. Hence, it means that in order to find the center we have to minimize this eccentricity. 
 

Examples:  

Input: N = 4, Edges[] = { (1, 0), (1, 2), (1, 3)} 
Output:
Explanation: 

👁 Image

Input: N = 6, Edges[] = { (0, 3), (1, 3), (2, 3), (4, 3), (5, 4)} 
Output: 3, 4 
Explanation: 

👁 Image


Approach: It can be observed that the path of maximum eccentricity is the diameter of the tree. Hence, the center of the tree diameter will be the center of the tree as well.

Proof: 

  • For example, Let's consider a case where the longest path consists of odd number of vertices. Let the longest path be X ------ O -------- Y where X and Y are the two endpoints of the path and O is the middle vertex.
  • For a contradiction, if the center of the tree is not O but some other vertex O', then at least one of the following two statements must be true. 
    1. Path XO' is strictly longer than path XO
    2. Path YO' is strictly longer than path YO
  • This means O' will not satisfy the condition of minimum eccentricity. Hence by contradiction, we have proved that the center of the tree is actually the center of the diameter path.
  • Now if the diameter consists odd number of nodes, then there exists only 1 center (also known as Central Tree).
  • If diameter consists of even number of nodes, then there are 2 center nodes(also known as Bi-central Tree). 
     

Below is the implementation of the above approach:  


Output: 
1

 

Time Complexity: O(N) 
Auxiliary Space: O(N)

Comment
Article Tags: