Left-Right traversal of all the levels of N-ary tree

Given a Complete Binary Tree rooted at node 1, the task is to print the elements in the following defined order.

  1. First, print all elements of the last level in an alternate way such as first you print leftmost element and then rightmost element & continue in this until all elements are traversed of last level.
  2. Now do the same for the rest of the levels.

Examples:

Input:
            1
          /   \
        2      3
      /   \   /
     4     5 6
Output: 4 6 5 2 3 1
Explanation:
First print all elements of the last 
level which will be printed as follows: 4 6 5
Now tree becomes
       1
     /   \
    2     3
    
Now print elements as 2 3
Now the tree becomes: 1

Input:
        1
      /   \
     2     3
Output: 2 3 1

Approach:



  • Make a bfs call and store all the nodes present at level i int a vector array.
  • Also keep track of maximum level reached in a bfs call.
  • Now print the desired pattern starting from max level to 0

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation 
// for the above approach
#include <bits/stdc++.h>
using namespace std;
  
const int sz = 1e5;
int maxLevel = 0;
  
// Adjacency list 
// representation of the tree
vector<int> tree[sz + 1];
  
// Boolean array to mark all the
// vertices which are visited
bool vis[sz + 1];
  
// Integer array to store
// the level of each node
int level[sz + 1];
  
// Array of vector where ith index
// stores all the nodes at level i
vector<int> nodes[sz + 1];
  
// Utility function to create an
// edge between two vertices
void addEdge(int a, int b)
{
    // Add a to b's list
    tree[a].push_back(b);
  
    // Add b to a's list
    tree[b].push_back(a);
}
  
// Modified Breadth-First Function
void bfs(int node)
{
  // Create a queue of {child, parent}
  queue<pair<int, int> > qu;
  
  // Push root node in the front of
  // the queue and mark as visited
  qu.push({ node, 0 });
  nodes[0].push_back(node);
  vis[node] = true;
  level[1] = 0;
  
  while (!qu.empty()) {
  
    pair<int, int> p = qu.front();
    // Dequeue a vertex from queue
    qu.pop();
    vis[p.first] = true;
  
    // Get all adjacent vertices of the dequeued
    // vertex s. If any adjacent has not
    // been visited then enqueue it
    for (int child : tree[p.first]) {
        if (!vis[child]) {
            qu.push({ child, p.first });
            level[child] = level[p.first] + 1;
            maxLevel = max(maxLevel, level[child]);
            nodes[level[child]].push_back(child);
        }
    }
  }
}
  
// Function to display 
// the pattern
void display()
{
  for (int i = maxLevel; i >= 0; i--) {
    int len = nodes[i].size();
    // Printing all nodes
    // at given level
    for (int j = 0; j < len / 2; j++) {
        cout << nodes[i][j] << " " << nodes[i][len - 1 - j] << " ";
    }
    // If count of nodes
    // at level i is odd
    // print remaining node
    if (len % 2 == 1) {
        cout << nodes[i][len / 2] << " ";
    }
  }
}
  
// Driver code
int main()
{
  // Number of vertices
  int n = 6;
  
  addEdge(1, 2);
  addEdge(1, 3);
  addEdge(2, 4);
  addEdge(2, 5);
  addEdge(3, 6);
  
  // Calling modified bfs function
  bfs(1);
  
  display();
  
  return 0;
}

chevron_right


Output:

4 6 5 2 3 1


My Personal Notes arrow_drop_up

An Btech Computer Engineering undergraduate from Aligarh Muslim University

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.