Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Check if the given n-ary tree is a binary tree
Next article icon

Serialize and Deserialize an N-ary Tree

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file.

This post is mainly an extension of the below post. Serialize and Deserialize a Binary Tree

In an N-ary tree, there are no designated left and right children. An N-ary tree is represented by storing an array or list of child pointers with every node. 

The idea is to store an ‘end of children’ marker with every node. The following diagram shows serialization where ‘)’ is used as the end of the children’s marker. 

Following is the implementation of the above idea.  

C++
// A C++ Program serialize and deserialize an N-ary tree #include<cstdio> #define MARKER ')' #define N 5 using namespace std;  // A node of N-ary tree struct Node {    char key;    Node *child[N];  // An array of pointers for N children };  // A utility function to create a new N-ary tree node Node *newNode(char key) {     Node *temp = new Node;     temp->key = key;     for (int i = 0; i < N; i++)         temp->child[i] = NULL;     return temp; }  // This function stores the given N-ary tree in a file pointed by fp void serialize(Node *root, FILE *fp) {     // Base case     if (root == NULL) return;      // Else, store current node and recur for its children     fprintf(fp, "%c ", root->key);     for (int i = 0; i < N && root->child[i]; i++)          serialize(root->child[i],  fp);      // Store marker at the end of children     fprintf(fp, "%c ", MARKER); }  // This function constructs N-ary tree from a file pointed by 'fp'. // This function returns 0 to indicate that the next item is a valid // tree key. Else returns 0 int deSerialize(Node *&root, FILE *fp) {     // Read next item from file. If there are no more items or next     // item is marker, then return 1 to indicate same     char val;     if ( !fscanf(fp, "%c ", &val) || val == MARKER )        return 1;      // Else create node with this item and recur for children     root = newNode(val);     for (int i = 0; i < N; i++)       if (deSerialize(root->child[i], fp))          break;      // Finally return 0 for successful finish     return 0; }  // A utility function to create a dummy tree shown in above diagram Node *createDummyTree() {     Node *root = newNode('A');     root->child[0] = newNode('B');     root->child[1] = newNode('C');     root->child[2] = newNode('D');     root->child[0]->child[0] = newNode('E');     root->child[0]->child[1] = newNode('F');     root->child[2]->child[0] = newNode('G');     root->child[2]->child[1] = newNode('H');     root->child[2]->child[2] = newNode('I');     root->child[2]->child[3] = newNode('J');     root->child[0]->child[1]->child[0] = newNode('K');     return root; }  // A utility function to traverse the constructed N-ary tree void traverse(Node *root) {     if (root)     {         printf("%c ", root->key);         for (int i = 0; i < N; i++)             traverse(root->child[i]);     } }  // Driver program to test above functions int main() {     // Let us create an N-ary tree shown in above diagram     Node *root = createDummyTree();      // Let us open a file and serialize the tree into the file     FILE *fp = fopen("tree.txt", "w");     if (fp == NULL)     {         puts("Could not open file");         return 0;     }     serialize(root, fp);     fclose(fp);      // Let us deserialize the stored tree into root1     Node *root1 = NULL;     fp = fopen("tree.txt", "r");     deSerialize(root1, fp);      printf("Constructed N-Ary Tree from file is \n");     traverse(root1);      return 0; } 
Java
import java.io.*;  public class NAryTreeSerialization {     final static int N = 5;     final static char MARKER = ')';      // A node of N-ary tree     static class Node {         char key;         Node[] child; // An array of pointers for N children          Node(char key) {             this.key = key;             child = new Node[N];         }     }      // This function stores the given N-ary tree in a file pointed by fp     static void serialize(Node root, PrintWriter writer) {         // Base case         if (root == null) {             return;         }          // Else, store current node and recur for its children         writer.print(root.key + " ");         for (int i = 0; i < N && root.child[i] != null; i++) {             serialize(root.child[i], writer);         }          // Store marker at the end of children         writer.print(MARKER + " ");     }      // This function constructs N-ary tree from a file pointed by 'reader'.     static Node deSerialize(BufferedReader reader) throws IOException {         // Read next item from file. If there are no more items or next         // item is marker, then return null to indicate same         int val = reader.read();         if (val == -1 || val == MARKER) {             return null;         }         char c = (char) val;          // Else create node with this item and recur for children         Node root = new Node(c);         for (int i = 0; i < N; i++) {             root.child[i] = deSerialize(reader);             if (root.child[i] == null) {                 break;             }         }          return root;     }      // A utility function to create a dummy tree shown in above diagram     static Node createDummyTree() {         Node root = new Node('A');         root.child[0] = new Node('B');         root.child[1] = new Node('C');         root.child[2] = new Node('D');         root.child[0].child[0] = new Node('E');         root.child[0].child[1] = new Node('F');         root.child[2].child[0] = new Node('G');         root.child[2].child[1] = new Node('H');         root.child[2].child[2] = new Node('I');         root.child[2].child[3] = new Node('J');         root.child[0].child[1].child[0] = new Node('K');         return root;     }      // A utility function to traverse the constructed N-ary tree     static void traverse(Node root) {         if (root != null) {             System.out.print(root.key + " ");             for (int i = 0; i < N; i++) {                 traverse(root.child[i]);             }         }     }      // Driver program to test above functions     public static void main(String[] args) throws IOException {         // Let us create an N-ary tree shown in above diagram         Node root = createDummyTree();          // Let us open a file and serialize the tree into the file         PrintWriter writer = new PrintWriter(new FileWriter("tree.txt"));         serialize(root, writer);         writer.close();          // Let us deserialize the stored tree into root1         Node root1;         BufferedReader reader = new BufferedReader(new FileReader("tree.txt"));         root1 = deSerialize(reader);         reader.close();          System.out.println("Constructed N-Ary Tree from file is: ");         traverse(root1);         } } 
C#
using System; using System.IO;  public class GFG {     const int N = 5;     const char MARKER = ')';      // A node of N-ary tree     class Node {         public char key;         public Node[] child; // An array of pointers for N                              // children          public Node(char key)         {             this.key = key;             child = new Node[N];         }     }      // This function stores the given N-ary tree in a file     // pointed by fp     static void serialize(Node root, StreamWriter writer)     {         // Base case         if (root == null) {             return;         }          // Else, store current node and recur for its         // children         writer.Write(root.key + " ");         for (int i = 0; i < N && root.child[i] != null;              i++) {             serialize(root.child[i], writer);         }          // Store marker at the end of children         writer.Write(MARKER + " ");     }      // This function constructs N-ary tree from a file     // pointed by 'reader'.     static Node deSerialize(StreamReader reader)     {         // Read next item from file. If there are no more         // items or next item is marker, then return null to         // indicate same         int val = reader.Read();         if (val == -1 || val == MARKER) {             return null;         }         char c = (char)val;          // Else create node with this item and recur for         // children         Node root = new Node(c);         for (int i = 0; i < N; i++) {             root.child[i] = deSerialize(reader);             if (root.child[i] == null) {                 break;             }         }          return root;     }     // A utility function to create a dummy tree shown in     // above diagram     static Node createDummyTree()     {         Node root = new Node('A');         root.child[0] = new Node('B');         root.child[1] = new Node('C');         root.child[2] = new Node('D');         root.child[0].child[0] = new Node('E');         root.child[0].child[1] = new Node('F');         root.child[2].child[0] = new Node('G');         root.child[2].child[1] = new Node('H');         root.child[2].child[2] = new Node('I');         root.child[2].child[3] = new Node('J');         root.child[0].child[1].child[0] = new Node('K');         return root;     }      // A utility function to traverse the constructed N-ary     // tree     static void traverse(Node root)     {         if (root != null) {             Console.Write(root.key + " ");             for (int i = 0; i < N; i++) {                 traverse(root.child[i]);             }         }     }     // Driver program to test above functions     static void Main(string[] args)     {         // Let us create an N-ary tree shown in above         // diagram         Node root = createDummyTree();          // Let us open a file and serialize the tree into         // the file         StreamWriter writer = new StreamWriter("tree.txt");         serialize(root, writer);         writer.Close();          // Let us deserialize the stored tree into root1         Node root1;         StreamReader reader = new StreamReader("tree.txt");         root1 = deSerialize(reader);         reader.Close();          Console.WriteLine(             "Constructed N-Ary Tree from file is: ");         traverse(root1);     } } 
JavaScript
// Define a class for the Node of the N-ary tree class Node {     constructor(key) {         this.key = key;         this.children = [];     } }  // Utility function to create a new N-ary tree node function newNode(key) {     return new Node(key); }  // This function stores the given N-ary tree in a string function serialize(root) {     // Base case     if (!root) return "";      // Else, store current node and recur for its children     let serialized = root.key + " ";     for (const child of root.children) {         serialized += serialize(child);     }      // Store marker at the end of children     serialized += ") ";      return serialized; }  // This function constructs N-ary tree from a string. function deserialize(serialized) {     const values = serialized.split(" ");     let index = 0;      function buildTree() {         // Read next item from string. If there are no more items or next         // item is marker, then return null to indicate same         const value = values[index++];         if (!value || value === ")") return null;          // Else create node with this item and recur for children         const node = newNode(value);         while (true) {             const child = buildTree();             if (!child) break;             node.children.push(child);         }          // Finally return the node for successful finish         return node;     }      return buildTree(); }  // A utility function to create a dummy tree shown in above diagram function createDummyTree() {     const root = newNode('A');     root.children = [newNode('B'), newNode('C'), newNode('D')];     root.children[0].children = [newNode('E'), newNode('F')];     root.children[2].children = [newNode('G'), newNode('H'), newNode('I'), newNode('J')];     root.children[0].children[1].children = [newNode('K')];     return root; }  // A utility function to traverse the constructed N-ary tree function traverse(root) {     if (root) {         console.log(root.key, " ");         for (const child of root.children) {             traverse(child);         }     } }  // Driver program to test above functions function main() {     // Let us create an N-ary tree shown in above diagram     const root = createDummyTree();      // Let us serialize the tree into a string     const serializedTree = serialize(root);     console.log("Serialized N-Ary Tree: ", serializedTree);      // Let us deserialize the stored tree into root1     const root1 = deserialize(serializedTree);      console.log("Constructed N-Ary Tree from string is ");     traverse(root1); }  main(); 
Python3
# A Python program to serialize and deserialize an N-ary tree import sys  # A node of N-ary tree class Node:     def __init__(self, key):         self.key = key         self.children = []  # A utility function to create a new N-ary tree node def newNode(key):     temp = Node(key)     return temp  # This function stores the given N-ary tree in a file pointed by fp def serialize(root, fp):     # Base case     if not root:         return      # Else, store current node and recur for its children     fp.write(root.key + " ")     for child in root.children:         serialize(child, fp)      # Store marker at the end of children     fp.write(") ")  # This function constructs N-ary tree from a file pointed by 'fp'. # This function returns 0 to indicate that the next item is a valid # tree key. Else returns 0 def deSerialize(fp):     # Read next item from file. If there are no more items or next     # item is marker, then return None to indicate same     val = fp.read(1)     if not val or val == ")":         return None      # Else create node with this item and recur for children     root = newNode(val)     while True:         child = deSerialize(fp)         if not child:             break         root.children.append(child)      # Finally return the node for successful finish     return root  # A utility function to create a dummy tree shown in above diagram def createDummyTree():     root = newNode('A')     root.children = [newNode('B'), newNode('C'), newNode('D')]     root.children[0].children = [newNode('E'), newNode('F')]     root.children[2].children = [newNode('G'), newNode('H'), newNode('I'), newNode('J')]     root.children[0].children[1].children = [newNode('K')]     return root  # A utility function to traverse the constructed N-ary tree def traverse(root):     if root:         print(root.key, end=" ")         for child in root.children:             traverse(child)  # Driver program to test above functions def main():     # Let us create an N-ary tree shown in above diagram     root = createDummyTree()      # Let us open a file and serialize the tree into the file     fp = open("tree.txt", "w")     serialize(root, fp)     fp.close()      # Let us deserialize the stored tree into root1     fp = open("tree.txt", "r")     root1 = deSerialize(fp)     fp.close()      print("Constructed N-Ary Tree from file is ")     traverse(root1)  if __name__ == '__main__':     main() 

Output
Constructed N-Ary Tree from file is  A B E F K C D G H I J 

Time Complexity: O(N), where n is number of nodes.
Auxiliary Space: O(H+N) , where h is height of tree and n is number of nodes.

The above implementation can be optimized in many ways for example by using a vector in place of array of pointers. We have kept it this way to keep it simple to read and understand.

 



Next Article
Check if the given n-ary tree is a binary tree

V

varun
Improve
Article Tags :
  • DSA
  • Tree
  • n-ary-tree
Practice Tags :
  • Tree

Similar Reads

  • Introduction to Generic Trees (N-ary Trees)
    Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t
    5 min read
  • What is Generic Tree or N-ary Tree?
    Generic tree or an N-ary tree is a versatile data structure used to organize data hierarchically. Unlike binary trees that have at most two children per node, generic trees can have any number of child nodes. This flexibility makes them suitable for representing hierarchical data where each node can
    4 min read
  • N-ary Tree Traversals

    • Inorder traversal of an N-ary Tree
      Given an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples:  Input: N = 3   Output: 5 6 2 7 3 1 4Input: N = 3   Output: 2 3 5 1 4 6  Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finall
      6 min read

    • Preorder Traversal of an N-ary Tree
      Given an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree. Examples: Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 O
      14 min read

    • Iterative Postorder Traversal of N-ary Tree
      Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi
      10 min read

    • Level Order Traversal of N-ary Tree
      Given an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Output: 12 3 4 56 7 8 9 1011 12 1314Ex
      11 min read

    • ZigZag Level Order Traversal of an N-ary Tree
      Given a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
      8 min read

  • Depth of an N-Ary tree
    Given an n-ary tree containing positive node values, the task is to find the depth of the tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branch
    5 min read
  • Mirror of n-ary Tree
    Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. Th
    9 min read
  • Insertion in n-ary tree in given order and Level order traversal
    Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input:
    10 min read
  • Diameter of an N-ary tree
    The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded. Example 1: Example 2:  Prerequisite: Diameter of a binary tree. The path can either start from one of th
    15+ min read
  • Sum of all elements of N-ary Tree
    Given an n-ary tree consisting of n nodes, the task is to find the sum of all the elements in the given n-ary tree. Example: Input: Output: 268Explanation: The sum of all the nodes is 11 + 21 + 29 + 90 + 18 + 10 + 12 + 77 = 268 Input: Output: 360Explanation: The sum of all the nodes is 81 + 26 + 23
    5 min read
  • Serialize and Deserialize an N-ary Tree
    Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file. This post is mainly an
    11 min read
  • Easy problems on n-ary Tree

    • Check if the given n-ary tree is a binary tree
      Given an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multip
      6 min read

    • Largest element in an N-ary Tree
      Given an n-ary tree containing positive node values, the task is to find the node with the largest value in the given n-ary tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-a
      5 min read

    • Second Largest element in n-ary tree
      Given an n-ary tree containing positive node values, the task is to find the node with the second largest value in the given n-ary tree. If there is no second largest node return -1.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at
      7 min read

    • Number of children of given node in n-ary Tree
      Given a node x, find the number of children of x(if it exists) in the given n-ary tree. Example : Input : x = 50 Output : 3 Explanation : 50 has 3 children having values 40, 100 and 20. Approach : Initialize the number of children as 0.For every node in the n-ary tree, check if its value is equal to
      7 min read

    • Number of nodes greater than a given value in n-ary tree
      Given a n-ary tree and a number x, find and return the number of nodes which are greater than x. Example: In the given tree, x = 7 Number of nodes greater than x are 4. Approach: The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is gr
      6 min read

    • Check mirror in n-ary tree
      Given two n-ary trees, determine whether they are mirror images of each other. Each tree is described by e edges, where e denotes the number of edges in both trees. Two arrays A[]and B[] are provided, where each array contains 2*e space-separated values representing the edges of both trees. Each edg
      11 min read

    • Replace every node with depth in N-ary Generic Tree
      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
      15+ min read

    • Preorder Traversal of N-ary Tree Without Recursion
      Given an n-ary tree containing positive node values. The task is to print the preorder traversal without using recursion.Note: An n-ary tree is a tree where each node can have zero or more children. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows
      7 min read

    • Maximum value at each level in an N-ary Tree
      Given a N-ary Tree consisting of nodes valued in the range [0, N - 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}
      9 min read

    • Replace each node in given N-ary Tree with sum of all its subtrees
      Given an N-ary tree. The task is to replace the values of each node with the sum of all its subtrees and the node itself. Examples Input: 1 / | \ 2 3 4 / \ \ 5 6 7Output: Initial Pre-order Traversal: 1 2 5 6 7 3 4 Final Pre-order Traversal: 28 20 5 6 7 3 4 Explanation: Value of each node is replaced
      8 min read

    • Path from the root node to a given node in an N-ary Tree
      Given an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the
      10 min read

    • Determine the count of Leaf nodes in an N-ary tree
      Given the value of 'N' and 'I'. Here, [Tex]I [/Tex]represents the number of internal nodes present in an N-ary tree and every node of the N-ary can either have [Tex]N [/Tex]childs or zero child. The task is to determine the number of Leaf nodes in n-ary tree. Examples: Input : N = 3, I = 5 Output :
      4 min read

    • Remove all leaf nodes from a Generic Tree or N-ary Tree
      Given an n-ary tree containing positive node values, the task is to delete all the leaf nodes from the tree and print preorder traversal of the tree after performing the deletion.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at mo
      6 min read

    • Maximum level sum in N-ary Tree
      Given an N-ary Tree consisting of nodes valued [1, N] and an array value[], where each node i is associated with value[i], the task is to find the maximum of sum of all node values of all levels of the N-ary Tree. Examples: Input: N = 8, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6},
      9 min read

    • Number of leaf nodes in a perfect N-ary tree of height K
      Find the number of leaf nodes in a perfect N-ary tree of height K. Note: As the answer can be very large, return the answer modulo 109+7. Examples: Input: N = 2, K = 2Output: 4Explanation: A perfect Binary tree of height 2 has 4 leaf nodes. Input: N = 2, K = 1Output: 2Explanation: A perfect Binary t
      4 min read

    • Print all root to leaf paths of an N-ary tree
      Given an N-Ary tree, the task is to print all root to leaf paths of the given N-ary Tree. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 Output:1 2 41 3 51 3 6 71 3 6 8 Input: 1 / | \ 2 5 3 / \ \ 4 5 6Output:1 2 41 2 51 51 3 6 Approach: The idea to solve this problem is to start traversing the N-ary
      7 min read

    • Minimum distance between two given nodes in an N-ary tree
      Given a N ary Tree consisting of N nodes, the task is to find the minimum distance from node A to node B of the tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8A = 4, B = 3Output: 3Explanation: The path 4->2->1->3 gives the minimum distance from A to B. Input: 1 / \ 2 3 / \ \ 6 7 8A = 6,
      11 min read

    • Average width in a N-ary tree
      Given a Generic Tree consisting of N nodes, the task is to find the average width for each node present in the given tree. The average width for each node can be calculated by the ratio of the total number of nodes in that subtree(including the node itself) to the total number of levels under that n
      8 min read

    • Maximum width of an N-ary tree
      Given an N-ary tree, the task is to find the maximum width of the given tree. The maximum width of a tree is the maximum of width among all levels. Examples: Input: 4 / | \ 2 3 -5 / \ /\ -1 3 -2 6 Output: 4 Explanation: Width of 0th level is 1. Width of 1st level is 3. Width of 2nd level is 4. There
      9 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences