VOOZH about

URL: https://www.geeksforgeeks.org/dsa/replace-every-node-with-depth-in-n-ary-generic-tree/

⇱ Replace every node with depth in N-ary Generic Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Replace every node with depth in N-ary Generic Tree

Last Updated : 12 Jul, 2025

Given an arrayarr[] representing a Generic(N-ary) tree. The task is to replace the node data with the depth(level) of the node. Assume level of root to be 0.

Array Representation: The N-ary tree is serialized in the array arr[] using level order traversal as described below: 

  • The input is given as a level order traversal of N-ary Tree.
  • The first element of the array arr[] is the root node.
  • Then, followed by a number N, which denotes the number of children of the previous node. Value zero denotes Null Node.


Examples:

Input: arr[] = { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 } 
Below is the N-ary Tree of the above array level order traversal: 

👁 NarrayTreeExample1


Output:
Below is the representation of the above output:  

👁 NarrayTreeExample1Solution


Input: arr[] = {1, 3, 2, 3, 4, 2, 5, 6, 0, 0, 2, 8, 9, 0} 
Below is the N-ary Tree of the above array level order traversal: 

👁 example-1


Output:
Below is the representation of the above output: 


👁 example-2

Approach:

  • Traverse the tree starting from root.
  • While traversing pass depth of node as a parameter.
  • Track depth by passing it as 0 for root and (1 + current level) for children.

Below is the implementation of the above approach:


Output
0 
1 1 1 
2 2 
3 3 

Time Complexity: O(N), where N is the number of nodes in Tree. 
Auxiliary Space: O(N), where N is the number of nodes in Tree.

Another Approach: We can also replace the node's value with its depth while creating the tree. We are traversing the array level wise which means that nodes currently present in the queue are of the same depth. As we append its child nodes to the queue, they will be present in the next level. We can initialize a variable as current depth equal to 1 and when we create child node we can assign its value to current depth level. After traversing all the nodes present in the current level we will increment current depth level by 1.


Output
0 
1 1 1 
2 2 

Time Complexity: O(N), where N is the number of nodes in Tree. 
Auxiliary Space: O(N), where N is the number of nodes in Tree.

Comment
Article Tags: