# Replace every node with depth in N-ary Generic Tree

• Difficulty Level : Medium
• Last Updated : 11 Sep, 2021

Given an array arr[] 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:

Output:
Below is the representation of the above output:

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

Output:
Below is the representation of the above output:

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:

## CPP

 // C++ program to implement node with // it's depth value #include using namespace std;   // Treenode class using template template class TreeNode { public:     // To store node value     T data;       // Pointer to TreeNode to store     // the child node     vector*> children;       // Constructor to assign data     // to node     TreeNode(T data)     {         this->data = data;     }       // Destructors to delete a node     ~TreeNode()     {         for (int i = 0;              i < children.size(); i++) {             delete children[i];         }     } };   // Function to take input level wise // i.e., in level order traversal TreeNode* takeInputLevelWise(int arr[]) {     int idx = 1;       // Input root     int rootData = arr[0];       // Initialize tree with a root node     TreeNode* root         = new TreeNode(rootData);       // Initialise queue for appending     // node as a child of parent in     // N-ary tree     queue*> pendingNodes;       // Push the root node in queue     pendingNodes.push(root);       // While queue is not empty append     // child to the root     while (pendingNodes.size() != 0) {           // Take the first node         TreeNode* front             = pendingNodes.front();         pendingNodes.pop();           // Input number of child         int numChild = arr[idx];         idx++;           for (int i = 0; i < numChild; i++) {               int childData = arr[idx];             idx++;               // Make child Node             TreeNode* child                 = new TreeNode(childData);               // Append child node to             // it's parent             front->children.push_back(child);             pendingNodes.push(child);         }     }     return root; }   // Function to print each node data // in level order void printLevelATNewLine(TreeNode* root) {     queue*> q;     q.push(root);     q.push(NULL);     while (!q.empty()) {           TreeNode* first = q.front();         q.pop();           if (first == NULL) {             if (q.empty()) {                 break;             }             cout << endl;             q.push(NULL);             continue;         }           cout << first->data << " ";           for (int i = 0;              i < first->children.size(); i++) {             q.push(first->children[i]);         }     } }   // Helper function to replace the // node data with their level value void helper(TreeNode* root,             int depth) {       // Replace the node data with     // it's depth     root->data = depth;     for (int i = 0;          i < root->children.size(); i++) {           helper(root->children[i], depth + 1);     } }   // Function to replace with depth void replaceWithDepthValue(TreeNode* root) {     helper(root, 0); }   // Driver Code int main() {       // Given level order traversal in     // the array arr[]     int arr[] = { 10, 3, 20, 30, 40, 2,                   40, 50, 0, 0, 0, 0 };       // Initialise Tree     TreeNode* root;     root = takeInputLevelWise(arr);       // Function call to replace with     // depth value     replaceWithDepthValue(root);       // Function call to print     // in level order     printLevelATNewLine(root);     return 0; }

## Java

 // Java program to replace node with // it's depth value   // Importing classes and interface import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue;   class GFG {     // TreeNode class     static class TreeNode {         // To store node value         T data;           // List of TreeNode to store         // the child nodes         ArrayList > children;           // Constructor to assign data to node         TreeNode(T data)         {             this.data = data;             children = new ArrayList >();         }     }       // Function to take input level wise     // i.e., in level order traversal     static TreeNode takeInputLevelWise(int arr[])     {         int idx = 1;           // Input root         int rootData = arr[0];           // Initialize tree with a root node         TreeNode root             = new TreeNode(rootData);           // Initialize queue for appending         // node as a child of parent in         // N-ary tree         Queue > pendingNodes             = new LinkedList >();           // Push the root node in queue         pendingNodes.add(root);           // While queue is not empty append         // child to the node         while (pendingNodes.size() != 0) {               // Take the first node             TreeNode front = pendingNodes.peek();             pendingNodes.poll();               // Input number of its child             int numChild = arr[idx];             idx++;               for (int i = 0; i < numChild; i++) {                 int childData = arr[idx];                 idx++;                   // Make child Node                 TreeNode child                     = new TreeNode(childData);                   // Append child node to                 // it's parent                 front.children.add(child);                 pendingNodes.add(child);             }         }         return root;     }       // Function to print each node data     // in level order     static void printLevelATNewLine(TreeNode root)     {         Queue > q             = new LinkedList >();         q.add(root);         q.add(null);         while (!q.isEmpty()) {             TreeNode first = q.peek();             q.poll();               if (first == null) {                 // If there is no more nodes                 if (q.isEmpty()) {                     break;                 }                 // All the nodes of current level are                 // visited                 System.out.println();                 q.add(null);                 continue;             }               System.out.print(first.data + " ");               // Append current node's child to queue             for (int i = 0; i < first.children.size();                  i++) {                 q.add(first.children.get(i));             }         }     }       // Helper function to replace the     // node data with their level value     static void helper(TreeNode root, int depth)     {         // Replace the node data with         // it's depth         root.data = depth;         for (int i = 0; i < root.children.size(); i++) {             helper(root.children.get(i), depth + 1);         }     }       // Function to replace with depth     static void     replaceWithDepthValue(TreeNode root)     {         helper(root, 0);     }       // Driver Code     public static void main(String[] args)     {         // Given level order traversal in         // the array arr[]         int arr[]             = { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };           // Initialise Tree         TreeNode root;         root = takeInputLevelWise(arr);           // Function call to replace with         // depth value         replaceWithDepthValue(root);           // Function call to print         // in level order         printLevelATNewLine(root);     } }   // This code is contributed by jainlovely450

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.

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.

## C++

 // C++ program to implement node with // it's depth value #include using namespace std;   // Treenode class using template template class TreeNode { public:     // To store node value     T data;       // Pointer to TreeNode to store     // the child node     vector*> children;       // Constructor to assign data     // to node     TreeNode(T data) { this->data = data; }       // Destructors to delete a node     ~TreeNode()     {         for (int i = 0; i < children.size(); i++) {             delete children[i];         }     } };   // Function to take input level wise // i.e., in level order traversal TreeNode* takeInputLevelWise(int arr[]) {     int idx = 1;     int depthLevel = 1;       // Initialize tree with a root node     // with depth 0     TreeNode* root = new TreeNode(0);       // Initialise queue for appending     // node as a child of parent in     // N-ary tree     queue*> pendingNodes;       // Push the root node in queue     pendingNodes.push(root);       // While queue is not empty append     // child to the node     while (pendingNodes.size() != 0) {         // Number of nodes present in the current level         int size = pendingNodes.size();           while (size > 0) {             // Take the first node             TreeNode* front = pendingNodes.front();             pendingNodes.pop();               // Input number of its child             int numChild = arr[idx];             idx++;               for (int i = 0; i < numChild; i++) {                 idx++;                 // Make child Node and assign its data                 // value equal to depthLevel                 TreeNode* child                     = new TreeNode(depthLevel);                   // Append child node to                 // it's parent                 front->children.push_back(child);                 pendingNodes.push(child);             }             size--;         }         // Increment depth level         depthLevel++;     }     return root; }   // Function to print each node data // in level order void printLevelATNewLine(TreeNode* root) {     queue*> q;     q.push(root);     q.push(NULL);     while (!q.empty()) {         TreeNode* first = q.front();         q.pop();           if (first == NULL) {             // If there is no more nodes to visit             if (q.empty()) {                 break;             }             // All the nodes of current level are visited             cout << endl;             q.push(NULL);             continue;         }           cout << first->data << " ";         // Append current node's child to queue         for (int i = 0; i < first->children.size(); i++) {             q.push(first->children[i]);         }     } }   // Driver Code int main() {     // Given level order traversal in     // the array arr[]     int arr[]         = { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };       // Initialise Tree     TreeNode* root;     root = takeInputLevelWise(arr);       // Function call to print     // in level order     printLevelATNewLine(root);     return 0; }   // This code is contributed by jainlovely450

## Java

 // Java program to implement node with // it's depth value   // Importing classes and interface import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue;   public class GFG {       // TreeNode class     static class TreeNode {         // To store node value         T data;           // List of TreeNode to store         // the child nodes         ArrayList > children;           // Constructor to assign data to node         TreeNode(T data)         {             this.data = data;             children = new ArrayList >();         }     }       // Function to take input level wise     // i.e., in level order traversal and     // assign value of node equal to its depth     static TreeNode takeInputLevelWise(int arr[])     {         int idx = 1;         int depthLevel = 1;                 // Initialize tree with a root node         // with depth 0         TreeNode root = new TreeNode(0);                  // Initialize queue for appending         // node as a child of parent in         // N-ary tree         Queue > pendingNodes             = new LinkedList >();           // Push the root node in queue         pendingNodes.add(root);           // While queue is not empty append         // child to the node         while (!pendingNodes.isEmpty()) {             // Number of nodes present in the current level             int size = pendingNodes.size();               while (size > 0) {                 TreeNode front                     = pendingNodes.peek();                 pendingNodes.poll();                   // Input number of child                 int numChild = arr[idx];                 idx++;                 for (int i = 0; i < numChild; i++) {                     idx++;                       // Make child Node and assign its data                     // value equal to depthLevel                     TreeNode child                         = new TreeNode(depthLevel);                       // Append child node to                     // it's parent                     front.children.add(child);                     pendingNodes.add(child);                 }                 size--;             }             // Increment depth level             depthLevel++;         }         return root;     }       // Function to print each node data     // in level order     static void printLevelATNewLine(TreeNode root)     {         Queue > q             = new LinkedList >();         q.add(root);         q.add(null);         while (!q.isEmpty()) {             TreeNode first = q.peek();             q.poll();             if (first == null) {                 // If there is no more nodes to visit                 if (q.isEmpty()) {                     break;                 }                 // All the nodes of current level are                 // visited                 System.out.println();                 q.add(null);                 continue;             }               System.out.print(first.data + " ");               // Append current node's child to queue             for (int i = 0; i < first.children.size();                  i++) {                 q.add(first.children.get(i));             }         }     }       // Driver Code     public static void main(String[] args)     {           // Given level order traversal in         // the array arr[]         int arr[]             = { 10, 3, 20, 30, 40, 2, 40, 50, 0, 0, 0, 0 };           // Initialize Tree         TreeNode root;         root = takeInputLevelWise(arr);           // Function call to print         // in level order         printLevelATNewLine(root);     } }   // This code is contributed by jainlovely450

Output

0
1 1 1
2 2

My Personal Notes arrow_drop_up
Recommended Articles
Page :