Level order traversal by converting N-ary Tree into adjacency list representation with K as root node

Given the root node of an N-ary tree and an integer K, the task is to convert the given tree into adjacency list representation and print the level order traversal considering vertex K as the root node.
Example:
Input: Tree in the image below, K = 5
Output:
5Â
1 9 10 11Â
2 3 4Â
6 7 8Input: Tree in the image below, K = 5
Output:
5Â
1
2 3 4Â
7 8
Approach: The given problem can be solved by using the DFS Traversal on the N-ary tree and storing the relation of all the edges into an adjacency list according to the adjacency list representation. The created adjacency list can be used to print the Level Order Traversal with K as the root node. This can be done using BFS traversal which is discussed in this article.
Below is the implementation of the above approach:Â
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// A binary tree nodestruct Node {Â Â Â Â int data;Â Â Â Â vector<Node*> child;};Â
// Function to create a new tree nodeNode* newNode(int key){Â Â Â Â Node* temp = new Node;Â Â Â Â temp->data = key;Â Â Â Â return temp;}Â
// Adjacency list to store the Treevector<vector<int> > adj;Â
// Function to perform the DFS traversal// of the N-ary tree using the given// pointer to the root node of the treevoid DFS(struct Node* node){    // Traverse all child of node    for (auto x : node->child) {        if (x != NULL) {Â
            // Insert the pair of vertices            // into the adjacency list            adj[node->data].push_back(x->data);            adj[x->data].push_back(node->data);Â
            // Recursive call for DFS on x            DFS(x);        }    }}Â
// Function to print the level order// traversal of the given tree with// s as root nodevoid levelOrderTrav(int s, int N){    // Create a queue for Level    // Order Traversal    queue<int> q;Â
    // Stores if the current    // node is visited    vector<bool> visited(N);Â
    q.push(s);Â
    // -1 marks the end of level    q.push(-1);    visited[s] = true;    while (!q.empty()) {Â
        // Dequeue a vertex from queue        int v = q.front();        q.pop();Â
        // If v marks the end of level        if (v == -1) {            if (!q.empty())                q.push(-1);Â
            // Print a newline character            cout << endl;            continue;        }Â
        // Print current vertex        cout << v << " ";Â
        // Add the child vertices of        // the current node in queue        for (int u : adj[v]) {            if (!visited[u]) {                visited[u] = true;                q.push(u);            }        }    }}Â
// Driver Codeint main(){Â Â Â Â Node* root = newNode(1);Â Â Â Â (root->child).push_back(newNode(2));Â Â Â Â (root->child).push_back(newNode(3));Â Â Â Â (root->child).push_back(newNode(4));Â Â Â Â (root->child).push_back(newNode(5));Â Â Â Â (root->child[0]->child).push_back(newNode(6));Â Â Â Â (root->child[0]->child).push_back(newNode(7));Â Â Â Â (root->child[2]->child).push_back(newNode(8));Â Â Â Â (root->child[3]->child).push_back(newNode(9));Â Â Â Â (root->child[3]->child).push_back(newNode(10));Â Â Â Â (root->child[3]->child).push_back(newNode(11));Â Â Â Â int N = 11;Â Â Â Â int K = 5;Â Â Â Â adj.resize(N + 1, vector<int>());Â
    DFS(root);    levelOrderTrav(5, 11);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class Node {Â Â Â Â int data;Â Â Â Â ArrayList<Node> child;Â Â Â Â Node(int data)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.child = new ArrayList<>();Â Â Â Â }}Â
class Main {Â
    // Adjacency list to store the Tree    static List<List<Integer> > adj = new ArrayList<>();    // Function to perform the DFS traversal    // of the N-ary tree using the given    // pointer to the root node of the tree    static void DFS(Node node)    {        for (Node x : node.child) {            if (x != null) {                // Insert the pair of vertices                // into the adjacency list                adj.get(node.data).add(x.data);                adj.get(x.data).add(node.data);                // Recursive call for DFS on x                DFS(x);            }        }    }    // Function to print the level order    // traversal of the given tree with    // s as root node    static void levelOrderTrav(int s, int N)    {        // Create a queue for Level        // Order Traversal        Queue<Integer> q = new LinkedList<>();        // Stores if the current        // node is visited        boolean[] visited = new boolean[N + 1];Â
        q.offer(s);        // -1 marks the end of level        q.offer(-1);        visited[s] = true;        while (!q.isEmpty()) {            int v = q.poll();            if (v == -1) {                if (!q.isEmpty())                    q.offer(-1);                System.out.println();                continue;            }            // Print current vertex            System.out.print(v + " ");            // Add the child vertices of            // the current node in queue            for (int u : adj.get(v)) {                if (!visited[u]) {                    visited[u] = true;                    q.offer(u);                }            }        }    }Â
    public static void main(String[] args)    {        Node root = new Node(1);        root.child.add(new Node(2));        root.child.add(new Node(3));        root.child.add(new Node(4));        root.child.add(new Node(5));        root.child.get(0).child.add(new Node(6));        root.child.get(0).child.add(new Node(7));        root.child.get(2).child.add(new Node(8));        root.child.get(3).child.add(new Node(9));        root.child.get(3).child.add(new Node(10));        root.child.get(3).child.add(new Node(11));        int N = 11;        int K = 5;        for (int i = 0; i <= N; i++)            adj.add(new ArrayList<>());Â
        DFS(root);        levelOrderTrav(K, N);    }} |
Python
# Python program for the above approachfrom collections import defaultdict, dequeÂ
# A binary tree nodeclass Node:    def __init__(self, data):        self.data = data        self.child = []Â
# Function to create a new tree nodedef newNode(key):Â Â Â Â temp = Node(key)Â Â Â Â return tempÂ
# Adjacency list to store the Treeadj = defaultdict(list)Â
# Function to perform the DFS traversal# of the N-ary tree using the given# pointer to the root node of the treedef DFS(node):    # Traverse all child of node    for x in node.child:        if x:            # Insert the pair of vertices            # into the adjacency list            adj[node.data].append(x.data)            adj[x.data].append(node.data)            # Recursive call for DFS on x            DFS(x)Â
# Function to print the level order# traversal of the given tree with# s as root nodeÂ
Â
def levelOrderTrav(s, N):    # Create a queue for Level    # Order Traversal    q = deque()    # Stores if the current    # node is visited    visited = [False] * (N+1)Â
    q.append(s)    # -1 marks the end of level    q.append(-1)    visited[s] = True    while q:        # Dequeue a vertex from queue        v = q.popleft()        # If v marks the end of level        if v == -1:            if q:                q.append(-1)            # Print a newline character                         continue        # Print current vertex        print(v)        # Add the child vertices of        # the current node in queue        for u in adj[v]:            if not visited[u]:                visited[u] = True                q.append(u)Â
# Driver Codeif __name__ == "__main__":Â Â Â Â root = newNode(1)Â Â Â Â root.child.append(newNode(2))Â Â Â Â root.child.append(newNode(3))Â Â Â Â root.child.append(newNode(4))Â Â Â Â root.child.append(newNode(5))Â Â Â Â root.child[0].child.append(newNode(6))Â Â Â Â root.child[0].child.append(newNode(7))Â Â Â Â root.child[2].child.append(newNode(8))Â Â Â Â root.child[3].child.append(newNode(9))Â Â Â Â root.child[3].child.append(newNode(10))Â Â Â Â root.child[3].child.append(newNode(11))Â Â Â Â N = 11Â Â Â Â K = 5Â Â Â Â DFS(root)Â Â Â Â levelOrderTrav(5, 11)Â
    # This code is contributed by aadityamaharshi21. |
C#
using System;using System.Collections.Generic;Â
// Node class definitionclass Node {    // Data members    public int data;    public List<Node> child;Â
    // Constructor    public Node(int data)    {        this.data = data;        this.child = new List<Node>();    }}Â
class GFG {    // Adjacency list to store the Tree    static List<List<int> > adj = new List<List<int> >();Â
    // Function to perform the DFS traversal    // of the N-ary tree using the given    // pointer to the root node of the tree    static void DFS(Node node)    {        foreach(Node x in node.child)        {            if (x != null) {                // Insert the pair of vertices                // into the adjacency list                adj[node.data].Add(x.data);                adj[x.data].Add(node.data);                // Recursive call for DFS on x                DFS(x);            }        }    }Â
    // Function to print the level order    // traversal of the given tree with    // s as root node    static void LevelOrderTrav(int s, int N)    {        // Create a queue for Level        // Order Traversal        Queue<int> q = new Queue<int>();        // Stores if the current        // node is visited        bool[] visited = new bool[N + 1];Â
        q.Enqueue(s);        // -1 marks the end of level        q.Enqueue(-1);        visited[s] = true;        while (q.Count > 0) {            int v = q.Dequeue();            if (v == -1) {                if (q.Count > 0)                    q.Enqueue(-1);                Console.WriteLine();                continue;            }            // Print current vertex            Console.Write(v + " ");            // Add the child vertices of            // the current node in queue            foreach(int u in adj[v])            {                if (!visited[u]) {                    visited[u] = true;                    q.Enqueue(u);                }            }        }    }Â
    // Driver code    public static void Main(string[] args)    {        // Building the tree        Node root = new Node(1);        root.child.Add(new Node(2));        root.child.Add(new Node(3));        root.child.Add(new Node(4));        root.child.Add(new Node(5));        root.child[0].child.Add(new Node(6));        root.child[0].child.Add(new Node(7));        root.child[2].child.Add(new Node(8));        root.child[3].child.Add(new Node(9));        root.child[3].child.Add(new Node(10));        root.child[3].child.Add(new Node(11));        int N = 11;        int K = 5;        for (int i = 0; i <= N; i++)            adj.Add(new List<int>());Â
        // Function calls        DFS(root);        LevelOrderTrav(K, N);    }} |
Javascript
       // JavaScript code for the above approach       // A class to represent a tree node       class Node {           constructor(data) {               this.data = data;               this.children = [];           }       }Â
       // Adjacency list to store the tree       const adj = [];Â
       // Function to perform the DFS traversal       // of the N-ary tree using the given       // pointer to the root node of the tree       function DFS(node) {           // Traverse all children of node           for (const child of node.children) {               if (child != null)                {                                   // Insert the pair of vertices                   // into the adjacency list                   adj[node.data].push(child.data);                   adj[child.data].push(node.data);Â
                   // Recursive call for DFS on child                   DFS(child);               }           }       }Â
       // Function to print the level order       // traversal of the given tree with       // s as root node       function levelOrderTrav(s, N)       {                   // Create a queue for Level           // Order Traversal           const q = [];Â
           // Stores if the current           // node is visited           const visited = new Array(N).fill(false);Â
           q.push(s);Â
           // -1 marks the end of level           q.push(-1);           visited[s] = true;           while (q.length > 0) {               // Dequeue a vertex from queue               const v = q.shift();Â
               // If v marks the end of level               if (v === -1) {                   if (q.length > 0) {                       q.push(-1);                   }Â
                   // Print a newline character                   document.write("<br>");                   continue;               }Â
               // Print current vertex               document.write(v + " ");Â
               // Add the child vertices of               // the current node in queue               for (const u of adj[v]) {                   if (!visited[u]) {                       visited[u] = true;                       q.push(u);                   }               }           }       }Â
       // Create the N-ary tree       const root = new Node(1);       root.children.push(new Node(2));       root.children.push(new Node(3));       root.children.push(new Node(4));       root.children.push(new Node(5));       root.children[0].children.push(new Node(6));       root.children[0].children.push(new Node(7));       root.children[2].children.push(new Node(8));       root.children[3].children.push(new Node(9));       root.children[3].children.push(new Node(10));       root.children[3].children.push(new Node(11));       const N = 11;       const K = 5;Â
       // Initialize the adjacency list       for (let i = 0; i <= N; i++) {           adj.push([]);       }Â
       // Perform DFS on the tree       DFS(root);Â
       // Print the tree in level order traversal       levelOrderTrav(5, 11);Â
// This code is contributed by Potta Lokesh. |
5 1 9 10 11 2 3 4 6 7 8
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




