Open In App

Introduction to Generic Trees (N-ary Trees)

Last Updated : 20 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 the very first node’s address will be stored in a separate pointer called root.

The Generic trees are the N-ary trees which have the following properties: 

            1. Many children at every node.

            2. The number of nodes for each node is not known in advance.

Example: 
 

Generic Tree

To represent the above tree, we have to consider the worst case, that is the node with maximum children (in above example, 6 children) and allocate that many pointers for each node.
The node representation based on this method can be written as:
 

C++




// Node declaration
struct Node{
   int data;
   Node *firstchild;
   Node *secondchild;
   Node *thirdchild;
   Node *fourthchild;
   Node *fifthchild;
   Node *sixthchild;
};


C




//Node declaration
struct Node{
   int data;
   struct Node *firstchild;
   struct Node *secondchild;
   struct Node *thirdchild;
   struct Node *fourthchild;
   struct Node *fifthchild;
   struct Node *sixthchild;
}


Java




// Java code for above approach
public class Node {
    int data;
    Node firstchild;
    Node secondchild;
    Node thirdchild;
    Node fourthchild;
    Node fifthchild;
    Node sixthchild;
}


Python




class Node:
    def __init__(self, data):
        self.data = data
        self.firstchild = None
        self.secondchild = None
        self.thirdchild = None
        self.fourthchild = None
        self.fifthchild = None
        self.sixthchild = None


C#




public class Node
{
    public int Data { get; set; }
    public Node Firstchild { get; set; }
    public Node Secondchild { get; set; }
    public Node Thirdchild { get; set; }
    public Node Fourthchild { get; set; }
    public Node Fifthchild { get; set; }
    public Node Sixthchild { get; set; }
}


Javascript




// Javascript code for above approach
class Node {
    constructor(data) {
        this.data = data;
        this.firstchild = null;
        this.secondchild = null;
        this.thirdchild = null;
        this.fourthchild = null;
        this.fifthchild = null;
        this.sixthchild = null;
    }
}


Disadvantages of the above representation are: 

  1. Memory Wastage – All the pointers are not required in all the cases. Hence, there is lot of memory wastage.
  2. Unknown number of children – The number of children for each node is not known in advance.

Simple Approach: 

For storing the address of children in a node we can use an array or linked list. But we will face some issues with both of them.

  1. In Linked list, we can not randomly access any child’s address. So it will be expensive.
  2. In array, we can randomly access the address of any child, but we can store only fixed number of children’s addresses in it.

Better Approach:

We can use Dynamic Arrays for storing the address of children. We can randomly access any child’s address and the size of the vector is also not fixed.

C++




#include <vector>
  
class Node {
public:
    int data;
    std::vector<Node*> children;
  
    Node(int data)
    {
        this->data = data;
    }
};


C




//Node declaration
struct Node{
    int data;
    vector<Node*> children;
}


Java




import java.util.ArrayList;
  
class Node {
    int data;
    ArrayList<Node> children;
  
    Node(int data)
    {
        this.data = data;
        this.children = new ArrayList<Node>();
    }
}


Python




class Node:
      
    def __init__(self,data):
        self.data=data
        self.children=[]


C#




using System.Collections.Generic;
  
class Node {
    public int data;
    public List<Node> children;
  
    public Node(int data)
    {
        this.data = data;
        this.children = new List<Node>();
    }
}
  
// This code is contributed by adityamaharshi21.


Javascript




class Node {
  constructor(data) {
    this.data = data;
    this.children = [];
  }
}


Efficient Approach:  

First child / Next sibling representation

 In the first child/next sibling representation, the steps taken are: 

At each node-link the children of the same parent(siblings) from left to right.

  • Remove the links from parent to all children except the first child.

Since we have a link between children, we do not need extra links from parents to all the children. This representation allows us to traverse all the elements by starting at the first child of the parent.
 

FIRST CHILD/NEXT SIBLING REPRESENTATION

The node declaration for first child / next sibling representation can be written as: 
 

C++




struct Node {
    int data;
    Node *firstChild;
    Node *nextSibling;
};


C




//Node declaration
struct Node{
    int data;
    struct Node *firstChild;
    struct Node *nextSibling;
}


Java




class Node {
    int data;
    Node firstChild;
    Node nextSibling;
}


Python




class Node:
    def __init__(self, data):
        self.data = data
        self.firstChild = None
        self.nextSibling = None
  
        # This code is contributed by aadityamaharshi


Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.firstChild = null;
        this.nextSibling = null;
    }
}


C#




public class Node {
    public int Data
    {
        get;
        set;
    }
    public Node FirstChild
    {
        get;
        set;
    }
    public Node NextSibling
    {
        get;
        set;
    }
}


Advantages: 

  • Memory efficient – No extra links are required, hence a lot of memory is saved.
  • Treated as binary trees – Since we are able to convert any generic tree to binary representation, we can treat all generic trees with a first child/next sibling representation as binary trees. Instead of left and right pointers, we just use firstChild and nextSibling.
  • Many algorithms can be expressed more easily because it is just a binary tree.
  • Each node is of fixed size ,so no auxiliary array or vector is required.

Height of generic tree from parent array 
Generic tree – level order traversal



Similar Reads

Check if given Generic N-ary Tree is Symmetric horizontally
Given an N-ary tree root, the task is to check if it is symmetric horizontally (Mirror image of itself). Example: Input: root = 7 / / \ \ 4 2 2 4 / | / | | \ | \ 3 2 6 7 7 6 2 3Output: trueExplanation: The left side of the tree is a mirror image of the right side Input: root= 2 / | \ 3 4 3 / | \ 5 6 5Output: true Approach: The given problem can be
8 min read
Remove all leaf nodes from a Generic Tree or N-ary Tree
Given a Generic tree, the task is to delete the leaf nodes from the tree. Examples: Input: 5 / / \ \ 1 2 3 8 / / \ \ 15 4 5 6 Output: 5 : 1 2 3 1 : 2 : 3 : Explanation: Deleted leafs are: 8, 15, 4, 5, 6 Input: 8 / | \ 9 7 2 / | \ | / / | \ \ 4 5 6 10 11 1 2 2 3 Output: 8: 9 7 2 9: 7: 2: Approach: Follow the steps given below to solve the problem Co
9 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 a level order traversal of N-ary Tree.The first e
15+ min read
DP on Trees | Set-3 ( Diameter of N-ary Tree )
Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: Example 2: Different approaches to solving these problems have already been discussed: https://www.geeksforgeeks.org/diameter-n-ary-tree/https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/ In
9 min read
Isomorphism in N-ary Trees
Given two N-ary trees having M nodes each. Also, given their edges and their roots respectively. The task is to check if they are isomorphic trees or not. If both the trees are isomorphic then print "Yes" else print "No". Examples: Input: M = 9, Root Node of tree-1: 1, Root Node of tree-2: 3 Edges of Tree-1: { (1, 3), (3, 4), (3, 5), (1, 8), (8, 9)
12 min read
LCA for general or n-ary trees (Sparse Matrix DP approach )
In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA) for a binary tree and a binary search tree (this, this and this). Now let’s look at a method that can calculate LCA for any tree (not only for binary tree). We use Dynamic Programming with Sparse Matrix Approach in our method. This method is very handy and fast w
15+ min read
Height of a generic tree from parent array
We are given a tree of size n as array parent[0..n-1] where every index i in the parent[] represents a node and the value at i represents the immediate parent of that node. For root node value will be -1. Find the height of the generic tree given the parent links. Examples: Input : parent[] = {-1, 0, 0, 0, 3, 1, 1, 2} Output : 2 Input : parent[] =
15+ min read
Generic Implementation of QuickSort Algorithm in C
Write a function to implement quicksort algorithm that will work for all types of data i.e ints, floats, chars etc. It should accept all types of data and show the sorted data as output. Note: This function is similar to C standard library function qsort(). Examples: First Input as a string. Input :abc cad bcd xyz bsd Output :abc bcd bsd cad xyz Se
4 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
How to Implement Generic LinkedList in Java?
Linked List is Linear Data Structures that store values in nodes. As we do know here each Node possesses two properties namely the value of the node and link to the next node if present so. Linked List can not only be of Integer data type but String, boolean, Float, Character, etc. We can implement such a “generic” Linked List Data Type that can st
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg