Open In App

ZigZag Level Order Traversal of an N-ary Tree

Last Updated : 25 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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 allows for multiple branches or children for each node.

Examples:

Input:

second-largest-element-in-n-ary-tree-1


Output:
11
90 29 21
18 10 12 77

Approach:

The idea is to solve the given problem by using BFS Traversal. The approach is very similar to the Level Order Traversal of the N-ary Tree. It can be observed that on reversing the order of the even levels during the Level Order Traversal, the obtained sequence is a ZigZag traversal.

Below is the implementation of the above approach:

C++
// C++ implementation of Zigzag order
// traversal of an N-ary tree using BFS
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    vector<Node*> children;
    
    Node(int val) {
        data = val;
    }
};

// Function to perform zigzag level
// order traversal
void zigzagTraversal(Node* root) {
  
    // Check if the tree is empty
    if (!root) return;

    queue<Node*> q;
 
    q.push(root);

    // Vector to store nodes of each level
    vector<vector<int>> result;

    while (!q.empty()) {
       
        int size = q.size();

        vector<int> curLevel;

        // Traverse all nodes in the current level
        for (int i = 0; i < size; i++) {

            Node* curr = q.front();
            q.pop();
            
            // Add the current node's value 
            // to the current level
            curLevel.push_back(curr->data);

            // Add all children of the current 
            // node to the queue
            for (auto child : curr->children) {
                q.push(child);
            }
        }

        // Store the current level in the result vector
        result.push_back(curLevel);
    }

    // Reverse the levels at even indices (0-based index)
    for (int i = 0; i < result.size(); i++) {
        
        // Reverse the level if it is at an odd index
        if (i % 2 != 0) {
            reverse(result[i].begin(), result[i].end());
        }
    }
  
    for (auto level : result) {
        for (int val : level) {
            cout << val << " ";
        }
        cout << endl;
    }
}

int main() {
    
     // Representation of given N-ary tree
    //         11
    //       /  |  \
    //     21   29  90
    //    /    /  \   \
    //   18   10  12  77
    Node* root = new Node(11);
    root->children.push_back(new Node(21));
    root->children.push_back(new Node(29));
    root->children.push_back(new Node(90));
    root->children[0]->children.push_back(new Node(18));
    root->children[1]->children.push_back(new Node(10));
    root->children[1]->children.push_back(new Node(12));
    root->children[2]->children.push_back(new Node(77));


    zigzagTraversal(root);

    return 0;
}
Java
// Java implementation of Zigzag order
// traversal of an N-ary tree using BFS
import java.util.*;

class Node {
    int data;
    List<Node> children;

    Node(int val) {
        data = val;
        children = new ArrayList<>();
    }
}

// Function to perform zigzag level order traversal
class GfG {

    static void zigzagTraversal(Node root) {

        // Check if the tree is empty
        if (root == null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        // List to store nodes of each level
        List<List<Integer>> result = new ArrayList<>();

        while (!q.isEmpty()) {

            int size = q.size();

            List<Integer> curLevel = new ArrayList<>();

            // Traverse all nodes in the current level
            for (int i = 0; i < size; i++) {

                Node curr = q.poll();

                // Add the current node's value
                curLevel.add(curr.data);

                // Add all children of the current
                // node to the queue
                for (Node child : curr.children) {
                    q.add(child);
                }
            }

            // Store the current level in the
           	// result list
            result.add(curLevel);
        }

        // Reverse the levels at even indices
       //(0-based index)
        for (int i = 0; i < result.size(); i++) {

            // Reverse the level if it is at an
          	// odd index
            if (i % 2 != 0) {
                Collections.reverse(result.get(i));
            }
        }

        // Print the zigzag level order traversal
        for (List<Integer> level : result) {
            for (int val : level) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {

        // Representation of given N-ary tree
        //         11
        //       /  |  \
        //     21   29  90
        //    /    /  \   \
        //   18   10  12  77
        Node root = new Node(11);
        root.children.add(new Node(21));
        root.children.add(new Node(29));
        root.children.add(new Node(90));
        root.children.get(0).children.add(new Node(18));
        root.children.get(1).children.add(new Node(10));
        root.children.get(1).children.add(new Node(12));
        root.children.get(2).children.add(new Node(77));

        zigzagTraversal(root);
    }
}
Python
# Python implementation of Zigzag order
# traversal of an N-ary tree using BFS
from collections import deque

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

# Function to perform zigzag level 
# order traversal
def zigzag_traversal(root):

    # Check if the tree is empty
    if not root:
        return

    q = deque()

    q.append(root)

    # List to store nodes of 
    # each level
    result = []

    while q:

        size = len(q)

        cur_level = []

        # Traverse all nodes in the current level
        for _ in range(size):

            curr = q.popleft()

            # Add the current node's value
            cur_level.append(curr.data)

            # Add all children of the current
            # node to the queue
            for child in curr.children:
                q.append(child)

        # Store the current level in the 
        # result list
        result.append(cur_level)

    # Reverse the levels at even indices 
    # (0-based index)
    for i in range(len(result)):

        # Reverse the level if it is at
        # an odd index
        if i % 2 != 0:
            result[i].reverse()

    # Print the zigzag level order traversal
    for level in result:
        print(" ".join(map(str, level)))
        
       
if __name__ == "__main__":
  
  # Representation of given N-ary tree
  #         11
  #       /  |  \
  #     21   29  90
  #    /    /  \   \
  #   18   10  12  77
  root = Node(11)
  root.children.append(Node(21))
  root.children.append(Node(29))
  root.children.append(Node(90))
  root.children[0].children.append(Node(18))
  root.children[1].children.append(Node(10))
  root.children[1].children.append(Node(12))
  root.children[2].children.append(Node(77))

  zigzag_traversal(root)
C#
// C# implementation of Zigzag order
// traversal of an N-ary tree using BFS
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public List<Node> children;

    public Node(int val) {
        data = val;
        children = new List<Node>();
    }
}

class GfG {

    // Function to perform zigzag level 
  	// order traversal
    static void ZigzagTraversalFunc(Node root) {

        // Check if the tree is empty
        if (root == null) return;

        Queue<Node> q = new Queue<Node>();

        q.Enqueue(root);

        // List to store nodes of each level
        List<List<int>> result = new List<List<int>>();

        while (q.Count > 0) {

            int size = q.Count;

            List<int> curLevel = new List<int>();

            // Traverse all nodes in the current level
            for (int i = 0; i < size; i++) {

                Node curr = q.Dequeue();

                // Add the current node's value
                curLevel.Add(curr.data);

                // Add all children of the current
                // node to the queue
                foreach (Node child in curr.children) {
                    q.Enqueue(child);
                }
            }

            result.Add(curLevel);
        }

        // Reverse the levels at even indices
      	// (0-based index)
        for (int i = 0; i < result.Count; i++) {

            // Reverse the level if it is at
          	// an odd index
            if (i % 2 != 0) {
                result[i].Reverse();
            }
        }
      
        foreach (var level in result) {
            foreach (int val in level) {
                Console.Write(val + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main(string[] args) {

       // Representation of given N-ary tree
        //         11
        //       /  |  \
        //     21   29  90
        //    /    /  \   \
        //   18   10  12  77
        Node root = new Node(11);
        root.children.Add(new Node(21));
        root.children.Add(new Node(29));
        root.children.Add(new Node(90));
        root.children[0].children.Add(new Node(18));
        root.children[1].children.Add(new Node(10));
        root.children[1].children.Add(new Node(12));
        root.children[2].children.Add(new Node(77));

        ZigzagTraversalFunc(root);
    }
}
JavaScript
// Javascript implementation of Zigzag order
// traversal of an N-ary tree using BFS
class Node {
    constructor(val) {
        this.data = val;
        this.children = [];
    }
}

// Function to perform zigzag level
// order traversal
function zigzagTraversal(root) {

    // Check if the tree is empty
    if (!root) return;

    const q = [];

    q.push(root);

    // Array to store nodes of 
    // each level
    const result = [];

    while (q.length > 0) {

        const size = q.length;

        const curLevel = [];

        // Traverse all nodes in the
        // current level
        for (let i = 0; i < size; i++) {

            const curr = q.shift();

            // Add the current node's value
            curLevel.push(curr.data);

            // Add all children of the current
            // node to the queue
            for (const child of curr.children) {
                q.push(child);
            }
        }
        
        result.push(curLevel);
    }

    // Reverse the levels at even indices
    // (0-based index)
    for (let i = 0; i < result.length; i++) {

        // Reverse the level if it is 
        // at an odd index
        if (i % 2 !== 0) {
            result[i].reverse();
        }
    }
    
    for (const level of result) {
        console.log(level.join(" "));
    }
}

// Representation of given N-ary tree
//         11
//       /  |  \
//     21   29  90
//    /    /  \   \
//   18   10  12  77
const root = new Node(11);
root.children.push(new Node(21));
root.children.push(new Node(29));
root.children.push(new Node(90));
root.children[0].children.push(new Node(18));
root.children[1].children.push(new Node(10));
root.children[1].children.push(new Node(12));
root.children[2].children.push(new Node(77));
zigzagTraversal(root);

Output
11 
90 29 21 
18 10 12 77 

Time Complexity: O(n), where n is the number of nodes in the tree, as each node is processed once during the traversal.
Auxiliary Space: O(n), where n is the maximum number of nodes at any level in the tree, which is required for the queue and result storage.


Next Article

Similar Reads