Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 31 Jan, 2023
Improve Article
Save Article

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:

1 9 10 11 
2 3 4 
6 7 8

Input: Tree in the image below, K = 5

Output:

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 node
struct Node {
    int data;
    vector<Node*> child;
};
 
// Function to create a new tree node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->data = key;
    return temp;
}
 
// Adjacency list to store the Tree
vector<vector<int> > adj;
 
// Function to perform the DFS traversal
// of the N-ary tree using the given
// pointer to the root node of the tree
void 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 node
void 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 Code
int 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;
}


Python




# Python program for the above approach
from collections import defaultdict, deque
 
# A binary tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.child = []
 
# Function to create a new tree node
def newNode(key):
    temp = Node(key)
    return temp
 
# Adjacency list to store the Tree
adj = defaultdict(list)
 
# Function to perform the DFS traversal
# of the N-ary tree using the given
# pointer to the root node of the tree
def 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 Code
if __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.


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.


Output:

5 
1 9 10 11 
2 3 4 
6 7 8

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!