Level order traversal with direction change after every two levels | Recursive Approach

Given a binary tree, print the level order traversal in such a way that first two levels are printed from left to right, next two levels are printed from right to left, then next two from left to right and so on. So, the problem is to reverse the direction of level order traversal of the binary tree after every two levels.

Examples:

Input: 
            1     
          /   \
        2       3
      /  \     /  \
     4    5    6    7
    / \  / \  / \  / \ 
   8  9 3   1 4  2 7  2
     /     / \    \
    16    17  18   19
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
In the above example, the first two levels
are printed from left to right, next two
levels are printed from right to left,
and then the last level is printed from 
left to right.

Approach: In the previous post, level order traversal using queue and stack has been done to print the elements. A recursive method has been used over here to print the elements in every level. Traverse every level in the tree, for every level, check the direction. Use a flag to know the direction of traversal in the tree. If the flag is set to true, print the nodes from right to left in the particular level. If the flag is set to false, print the nodes in that level from left to right. Initially, the flag is set to False, after every 2 levels, flag changes its value to true and vice versa.



Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program level order traversal
// with direction change
// after every two levels
#include <bits/stdc++.h>
using namespace std;
  
struct node {
    int data;
    node *left, *right;
} * temp;
  
// inserts new node
node* newNode(int data)
{
    temp = new node;
    temp->data = data;
    temp->left = temp->right = NULL;
  
    return temp;
}
  
// function to  print current level
void printCurrLevel(node* root, int level, bool flag)
{
    if (!root)
        return;
  
    if (level == 1) {
        cout << root->data << " ";
        return;
    }
  
    else {
        // If the flag is true, we have to print
        // level from RIGHT to LEFT.
        if (flag) {
            printCurrLevel(root->right, level - 1, flag);
            printCurrLevel(root->left, level - 1, flag);
        }
  
        // If the flag is false, we have to print
        // level from LEFT to RIGHT.
        else {
            printCurrLevel(root->left, level - 1, flag);
            printCurrLevel(root->right, level - 1, flag);
        }
    }
}
  
// This function returns the height of tree.
int height(node* root)
{
    if (!root)
        return 0;
  
    // left subtree
    int lh = height(root->left);
  
    // right subtree
    int rh = height(root->right);
  
    return 1 + max(lh, rh);
}
  
// Fucntion to traverse level-wise and
// print nodes
void modifiedLevelOrder(node* root)
{
    int h = height(root);
  
    // Variable to choose direction.
    bool flag = false;
    for (int i = 1; i <= h; i++) {
        printCurrLevel(root, i, flag);
        cout << endl;
  
        // change direction after every two levels.
        if (i % 2 == 0)
            flag = !flag;
    }
}
  
// Driver Code
int main()
{
  
    // create tree that is given
    // in the example
    node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->left->left = newNode(8);
    root->left->left->right = newNode(9);
    root->left->right->left = newNode(3);
    root->left->right->right = newNode(1);
    root->right->left->left = newNode(4);
    root->right->left->right = newNode(2);
    root->right->right->left = newNode(7);
    root->right->right->right = newNode(2);
    root->left->right->left->left = newNode(16);
    root->left->right->left->right = newNode(17);
    root->right->left->right->left = newNode(18);
    root->right->right->left->right = newNode(19);
  
    modifiedLevelOrder(root);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above idea 
import java.util.*;
  
class GFG 
{
      
static class node 
    int data; 
    node left, right; 
static node temp; 
  
// inserts new node 
static node newNode(int data) 
    temp = new node(); 
    temp.data = data; 
    temp.left = temp.right = null
  
    return temp; 
  
// function to print current level 
static void printCurrLevel(node root, int level, boolean flag) 
    if (root == null
        return
  
    if (level == 1
    
            System.out.print(root.data + " "); 
            return
    
  
    else
    
        // If the flag is true, we have to print 
        // level from RIGHT to LEFT. 
        if (flag) 
        
            printCurrLevel(root.right, level - 1, flag); 
            printCurrLevel(root.left, level - 1, flag); 
        
  
        // If the flag is false, we have to print 
        // level from LEFT to RIGHT. 
        else 
        
            printCurrLevel(root.left, level - 1, flag); 
            printCurrLevel(root.right, level - 1, flag); 
        
    
  
// This function returns the height of tree. 
static int height(node root) 
    if (root == null
        return 0
  
    // left subtree 
    int lh = height(root.left); 
  
    // right subtree 
    int rh = height(root.right); 
  
    return 1 + Math.max(lh, rh); 
  
// Fucntion to traverse level-wise and 
// print nodes 
static void modifiedLevelOrder(node root) 
    int h = height(root); 
  
    // Variable to choose direction. 
    boolean flag = false
    for (int i = 1; i <= h; i++) 
    
        printCurrLevel(root, i, flag); 
        System.out.println("");
  
        // change direction after every two levels. 
        if (i % 2 == 0
            flag = !flag; 
    
  
// Driver Code 
public static void main(String[] args)
{
    // create tree that is given 
    // in the example 
    node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(3); 
    root.left.left = newNode(4); 
    root.left.right = newNode(5); 
    root.right.left = newNode(6); 
    root.right.right = newNode(7); 
    root.left.left.left = newNode(8); 
    root.left.left.right = newNode(9); 
    root.left.right.left = newNode(3); 
    root.left.right.right = newNode(1); 
    root.right.left.left = newNode(4); 
    root.right.left.right = newNode(2); 
    root.right.right.left = newNode(7); 
    root.right.right.right = newNode(2); 
    root.left.right.left.left = newNode(16); 
    root.left.right.left.right = newNode(17); 
    root.right.left.right.left = newNode(18); 
    root.right.right.left.right = newNode(19); 
  
    modifiedLevelOrder(root); 
    }
}
  
// This code is contributed by Princi Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program level order traversal with
# direction change after every two levels 
class Node: 
      
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
      
# function to print current level 
def printCurrLevel(root, level, flag): 
  
    if root == None:
        return
  
    if level == 1
        print(root.data, end = " "
        return
  
    else:
          
        # If the flag is true, we have to 
        # print level from RIGHT to LEFT. 
        if flag: 
            printCurrLevel(root.right, 
                           level - 1, flag) 
            printCurrLevel(root.left, 
                           level - 1, flag) 
  
        # If the flag is false, we have to 
        # print level from LEFT to RIGHT. 
        else:
            printCurrLevel(root.left, 
                           level - 1, flag) 
            printCurrLevel(root.right, 
                           level - 1, flag) 
          
# This function returns the 
# height of tree. 
def height(root): 
  
    if root == None:
        return 0
  
    # left subtree 
    lh = height(root.left) 
  
    # right subtree 
    rh = height(root.right) 
  
    return 1 + max(lh, rh) 
  
# Function to traverse level-wise 
# and print nodes 
def modifiedLevelOrder(root): 
  
    h = height(root) 
  
    # Variable to choose direction. 
    flag = False
    for i in range(1, h + 1): 
        printCurrLevel(root, i, flag) 
        print() 
  
        # change direction after every 
        # two levels. 
        if i % 2 == 0
            flag = not flag 
  
# Driver Code 
if __name__ == "__main__"
  
    # create tree that is given 
    # in the example 
    root = Node(1
    root.left = Node(2
    root.right = Node(3
    root.left.left = Node(4
    root.left.right = Node(5
    root.right.left = Node(6
    root.right.right = Node(7
    root.left.left.left = Node(8
    root.left.left.right = Node(9
    root.left.right.left = Node(3
    root.left.right.right = Node(1
    root.right.left.left = Node(4
    root.right.left.right = Node(2
    root.right.right.left = Node(7
    root.right.right.right = Node(2
    root.left.right.left.left = Node(16
    root.left.right.left.right = Node(17
    root.right.left.right.left = Node(18
    root.right.right.left.right = Node(19
  
    modifiedLevelOrder(root) 
  
# This code is contributed by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of above idea 
using System;
  
class GFG 
      
public class node 
    public int data; 
    public node left, right; 
static node temp; 
  
// inserts new node 
static node newNode(int data) 
    temp = new node(); 
    temp.data = data; 
    temp.left = temp.right = null
  
    return temp; 
  
// function to print current level 
static void printCurrLevel(node root, int level, Boolean flag) 
    if (root == null
        return
  
    if (level == 1) 
    
        Console.Write(root.data + " "); 
        return
    
  
    else
    
        // If the flag is true, we have to print 
        // level from RIGHT to LEFT. 
        if (flag) 
        
            printCurrLevel(root.right, level - 1, flag); 
            printCurrLevel(root.left, level - 1, flag); 
        
  
        // If the flag is false, we have to print 
        // level from LEFT to RIGHT. 
        else
        
            printCurrLevel(root.left, level - 1, flag); 
            printCurrLevel(root.right, level - 1, flag); 
        
    
  
// This function returns the height of tree. 
static int height(node root) 
    if (root == null
        return 0; 
  
    // left subtree 
    int lh = height(root.left); 
  
    // right subtree 
    int rh = height(root.right); 
  
    return 1 + Math.Max(lh, rh); 
  
// Fucntion to traverse level-wise and 
// print nodes 
static void modifiedLevelOrder(node root) 
    int h = height(root); 
  
    // Variable to choose direction. 
    Boolean flag = false
    for (int i = 1; i <= h; i++) 
    
        printCurrLevel(root, i, flag); 
        Console.WriteLine(""); 
  
        // change direction after every two levels. 
        if (i % 2 == 0) 
            flag = !flag; 
    
  
// Driver Code 
public static void Main(String[] args) 
    // create tree that is given 
    // in the example 
    node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(3); 
    root.left.left = newNode(4); 
    root.left.right = newNode(5); 
    root.right.left = newNode(6); 
    root.right.right = newNode(7); 
    root.left.left.left = newNode(8); 
    root.left.left.right = newNode(9); 
    root.left.right.left = newNode(3); 
    root.left.right.right = newNode(1); 
    root.right.left.left = newNode(4); 
    root.right.left.right = newNode(2); 
    root.right.right.left = newNode(7); 
    root.right.right.right = newNode(2); 
    root.left.right.left.left = newNode(16); 
    root.left.right.left.right = newNode(17); 
    root.right.left.right.left = newNode(18); 
    root.right.right.left.right = newNode(19); 
  
    modifiedLevelOrder(root); 
  
/* This code is contributed by PrinciRaj1992 */

chevron_right


Output:

1 
2 3 
7 6 5 4 
2 7 2 4 1 3 9 8 
16 17 18 19


My Personal Notes arrow_drop_up

A Coding Enthusiast Rails Developer

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.