Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Reverse alternate levels of a perfect binary tree using Stack
Next article icon

Reverse alternate levels of a perfect binary tree

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a perfect binary tree, your task is to reverse the nodes present at alternate levels.

Examples:

Input: root = [1, 3, 2]
1
/ \
3 2
Output:
1
/ \
2 3
Explanation: Nodes at level 2 are reversed.

Input: root = [1, 2, 3, 4, 5, 6, 7]
1
/ \
2 3
/ \ / \
4 5 6 7
Output:
1
/ \
3 2
/ \ / \
4 5 6 7
Explanation: Nodes at level 2 are reversed. Level 1 and 3 remain as it is.

Table of Content

  • [Naive Approach] – Using Inorder Traversal – O(n) Time and O(n) Space
  • [Better Approach] – Using Breadth First Search – O(n) Time and O(n) Space
  • [Expected Approach] – Using Preorder Traversal – O(n) Time and O(log n) Space

[Naive Approach] – Using Inorder Traversal – O(n) Time and O(n) Space

The idea is to perform two Inorder Traversals, where in the first one we will store the nodes of the odd level in an auxiliary array, and in the second traversal we will put nodes back in a tree in reversed order. To do so, perform Inorder traversal and store the nodes in odd levels in an auxiliary array. Thereafter, traverse the tree again in an Inorder fashion. While traversing the tree, one by one take elements from last of the array and store them to every odd level traversed node. 

Below is given the implementation:

C++
// C++ program to reverse alternate  // levels of a binary tree #include<bits/stdc++.h> using namespace std;  // A Binary Tree node class Node {     public:     int data;     Node *left, *right;     Node(int data) {         this->data = data;         this->left = this->right = nullptr;     } };  // Function to store nodes of  // alternate levels in an array void storeAlternate(Node *root, vector<int> &arr, int lvl) {      // Base case     if (root == nullptr) return;      // Store elements of left subtree     storeAlternate(root->left, arr, lvl+1);      // Store this node only if this is a odd level node     if (lvl%2 != 0)         arr.push_back(root->data);      // Store elements of right subtree     storeAlternate(root->right, arr, lvl+1); }  // Function to modify Binary Tree void modifyTree(Node *root, vector<int> &arr, int lvl) {      // Base case     if (root == nullptr) return;      // Update nodes in left subtree     modifyTree(root->left, arr, lvl+1);      // Update this node only if this      // is an odd level node     if (lvl%2 != 0) {         root->data = arr.back();         arr.pop_back();     }      // Update nodes in right subtree     modifyTree(root->right, arr, lvl+1); }  // The main function to reverse  // alternate nodes of a binary tree void reverseAlternate(struct Node *root) {      // Create an auxiliary array to store      // nodes of alternate levels     vector<int> arr;      // First store nodes of alternate levels     storeAlternate(root, arr, 0);      // Update tree by taking elements from array     modifyTree(root, arr, 0); }  // A utility function to print indorder  // traversal of a binary tree void printInorder(struct Node *root) {     if (root == NULL) return;     printInorder(root->left);     cout << root->data << " ";     printInorder(root->right); }  int main() {     Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);     root->right->right = new Node(7);      cout << "Inorder Traversal of given tree\n";     printInorder(root);      reverseAlternate(root);      cout << "\nInorder Traversal of modified tree\n";     printInorder(root);      return 0; } 
Java
// Java program to reverse alternate  // levels of a binary tree import java.util.*;  class Node {     int data;     Node left, right;      Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // Function to store nodes of      // alternate levels in an array     static void storeAlternate(Node root, List<Integer> arr, int lvl) {          // Base case         if (root == null) return;          // Store elements of left subtree         storeAlternate(root.left, arr, lvl + 1);          // Store this node only if this is an odd level node         if (lvl % 2 != 0)             arr.add(root.data);          // Store elements of right subtree         storeAlternate(root.right, arr, lvl + 1);     }      // Function to modify Binary Tree     static void modifyTree(Node root, List<Integer> arr, int lvl) {          // Base case         if (root == null) return;          // Update nodes in left subtree         modifyTree(root.left, arr, lvl + 1);          // Update this node only if this          // is an odd level node         if (lvl % 2 != 0) {             root.data = arr.remove(arr.size() - 1);         }          // Update nodes in right subtree         modifyTree(root.right, arr, lvl + 1);     }      // The main function to reverse      // alternate nodes of a binary tree     static void reverseAlternate(Node root) {          // Create an auxiliary array to store          // nodes of alternate levels         List<Integer> arr = new ArrayList<>();          // First store nodes of alternate levels         storeAlternate(root, arr, 0);          // Update tree by taking elements from array         modifyTree(root, arr, 0);     }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         System.out.print(root.data + " ");         printInorder(root.right);     }      public static void main(String[] args) {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          System.out.println("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          System.out.println("\nInorder Traversal of modified tree");         printInorder(root);     } } 
Python
# Python program to reverse alternate  # levels of a binary tree  # A Binary Tree node class Node:     def __init__(self, data):         self.data = data         self.left = self.right = None  # Function to store nodes of  # alternate levels in an array def storeAlternate(root, arr, lvl):      # Base case     if root is None:         return      # Store elements of left subtree     storeAlternate(root.left, arr, lvl + 1)      # Store this node only if this is an odd level node     if lvl % 2 != 0:         arr.append(root.data)      # Store elements of right subtree     storeAlternate(root.right, arr, lvl + 1)  # Function to modify Binary Tree def modifyTree(root, arr, lvl):      # Base case     if root is None:         return      # Update nodes in left subtree     modifyTree(root.left, arr, lvl + 1)      # Update this node only if this      # is an odd level node     if lvl % 2 != 0:         root.data = arr.pop()      # Update nodes in right subtree     modifyTree(root.right, arr, lvl + 1)  # The main function to reverse  # alternate nodes of a binary tree def reverseAlternate(root):      # Create an auxiliary array to store      # nodes of alternate levels     arr = []      # First store nodes of alternate levels     storeAlternate(root, arr, 0)      # Update tree by taking elements from array     modifyTree(root, arr, 0)  # A utility function to print inorder  # traversal of a binary tree def printInorder(root):     if root is None:         return     printInorder(root.left)     print(root.data, end=" ")     printInorder(root.right)  # Driver Code if __name__ == "__main__":     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)      print("Inorder Traversal of given tree")     printInorder(root)      reverseAlternate(root)      print("\nInorder Traversal of modified tree")     printInorder(root) 
C#
// C# program to reverse alternate  // levels of a binary tree using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // Function to store nodes of      // alternate levels in an array     static void storeAlternate(Node root, List<int> arr, int lvl) {          // Base case         if (root == null) return;          // Store elements of left subtree         storeAlternate(root.left, arr, lvl + 1);          // Store this node only if this is an odd level node         if (lvl % 2 != 0)             arr.Add(root.data);          // Store elements of right subtree         storeAlternate(root.right, arr, lvl + 1);     }      // Function to modify Binary Tree     static void modifyTree(Node root, List<int> arr, int lvl) {          // Base case         if (root == null) return;          // Update nodes in left subtree         modifyTree(root.left, arr, lvl + 1);          // Update this node only if this          // is an odd level node         if (lvl % 2 != 0) {             root.data = arr[arr.Count - 1];             arr.RemoveAt(arr.Count - 1);         }          // Update nodes in right subtree         modifyTree(root.right, arr, lvl + 1);     }      // The main function to reverse      // alternate nodes of a binary tree     static void reverseAlternate(Node root) {          // Create an auxiliary array to store          // nodes of alternate levels         List<int> arr = new List<int>();          // First store nodes of alternate levels         storeAlternate(root, arr, 0);          // Update tree by taking elements from array         modifyTree(root, arr, 0);     }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         Console.Write(root.data + " ");         printInorder(root.right);     }      static void Main() {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          Console.WriteLine("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          Console.WriteLine("\nInorder Traversal of modified tree");         printInorder(root);     } } 
JavaScript
// JavaScript program to reverse alternate  // levels of a binary tree  // A Binary Tree node class Node {     constructor(data) {         this.data = data;         this.left = this.right = null;     } }  // Function to store nodes of  // alternate levels in an array function storeAlternate(root, arr, lvl) {      // Base case     if (root === null) return;      // Store elements of left subtree     storeAlternate(root.left, arr, lvl + 1);      // Store this node only if this is an odd level node     if (lvl % 2 !== 0)         arr.push(root.data);      // Store elements of right subtree     storeAlternate(root.right, arr, lvl + 1); }  // Function to modify Binary Tree function modifyTree(root, arr, lvl) {      // Base case     if (root === null) return;      // Update nodes in left subtree     modifyTree(root.left, arr, lvl + 1);      // Update this node only if this      // is an odd level node     if (lvl % 2 !== 0) {         root.data = arr.pop();     }      // Update nodes in right subtree     modifyTree(root.right, arr, lvl + 1); }  // The main function to reverse  // alternate nodes of a binary tree function reverseAlternate(root) {      // Create an auxiliary array to store      // nodes of alternate levels     let arr = [];      // First store nodes of alternate levels     storeAlternate(root, arr, 0);      // Update tree by taking elements from array     modifyTree(root, arr, 0); }  // A utility function to print inorder  // traversal of a binary tree function printInorder(root) {     if (root === null) return;     printInorder(root.left);     process.stdout.write(root.data + " ");     printInorder(root.right); }  // Driver Code let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7);  console.log("Inorder Traversal of given tree"); printInorder(root);  reverseAlternate(root);  console.log("\nInorder Traversal of modified tree"); printInorder(root); 

Output
Inorder Traversal of given tree 4 2 5 1 6 3 7  Inorder Traversal of modified tree 4 3 5 1 6 2 7 

Time Complexity: O(n), As it does two Inorder traversals of the binary tree.
Auxiliary Space: O(n), The extra space is used to store the odd level nodes of the tree and in recursive function call stack which is O(h), where h is the height of the tree.

[Better Approach] – Using Breadth First Search – O(n) Time and O(n) Space

The idea is to BFS to traverse the given tree in a level order fashion.

  • To do so, create a queue to store the nodes at each level. And for each level, we will pop all the nodes currently in the queue, which represent the nodes at the current level.
  • Then, we will push their children to the queue to represent the next level. This ensures that the queue always contains the nodes for just one level at a time.
  • When processing odd levels, we will collect the values of the nodes in an array, reverse that array, and then update the nodes’ values with the reversed values.
  • This step only happens for odd levels, while even levels remain unchanged.

Below is given the implementation:

C++
// C++ program to reverse alternate  // levels of a binary tree #include<bits/stdc++.h> using namespace std;  // A Binary Tree node class Node {     public:     int data;     Node *left, *right;     Node(int data) {         this->data = data;         this->left = this->right = nullptr;     } };   // The main function to reverse  // alternate nodes of a binary tree void reverseAlternate(Node *root) {      // Return if the tree is empty.     if (!root) {         return;       }      queue<Node*> q;      // Start BFS with the root node.     q.push(root);       int lvl = 0;      while (!q.empty()) {         int size = q.size();         vector<Node*> cur;          // Process all nodes at the current lvl.         for (int i = 0; i < size; i++) {             Node* node = q.front();             q.pop();             cur.push_back(node);              if (node->left) q.push(node->left);             if (node->right) q.push(node->right);         }          // Reverse node values if the current lvl is odd.         if (lvl % 2 == 1) {             int left = 0, right = cur.size() - 1;             while (left < right) {                 int temp = cur[left]->data;                 cur[left]->data = cur[right]->data;                 cur[right]->data = temp;                 left++;                 right--;             }         }          lvl++;     } }  // A utility function to print indorder  // traversal of a binary tree void printInorder(struct Node *root) {     if (root == NULL) return;     printInorder(root->left);     cout << root->data << " ";     printInorder(root->right); }  int main() {     Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);     root->right->right = new Node(7);      cout << "Inorder Traversal of given tree\n";     printInorder(root);      reverseAlternate(root);      cout << "\nInorder Traversal of modified tree\n";     printInorder(root);      return 0; } 
Java
// Java program to reverse alternate  // levels of a binary tree  import java.util.*;  class Node {     int data;     Node left, right;      Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // The main function to reverse      // alternate nodes of a binary tree     static void reverseAlternate(Node root) {          // Return if the tree is empty.         if (root == null) {             return;         }          Queue<Node> q = new LinkedList<>();          // Start BFS with the root node.         q.add(root);         int lvl = 0;          while (!q.isEmpty()) {             int size = q.size();             List<Node> cur = new ArrayList<>();              // Process all nodes at the current lvl.             for (int i = 0; i < size; i++) {                 Node node = q.poll();                 cur.add(node);                  if (node.left != null) q.add(node.left);                 if (node.right != null) q.add(node.right);             }              // Reverse node values if the current lvl is odd.             if (lvl % 2 == 1) {                 int left = 0, right = cur.size() - 1;                 while (left < right) {                     int temp = cur.get(left).data;                     cur.get(left).data = cur.get(right).data;                     cur.get(right).data = temp;                     left++;                     right--;                 }             }              lvl++;         }     }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         System.out.print(root.data + " ");         printInorder(root.right);     }      public static void main(String[] args) {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          System.out.println("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          System.out.println("\nInorder Traversal of modified tree");         printInorder(root);     } } 
Python
# Python program to reverse alternate  # levels of a binary tree  from collections import deque  class Node:     def __init__(self, data):         self.data = data         self.left = self.right = None  # The main function to reverse  # alternate nodes of a binary tree def reverseAlternate(root):      # Return if the tree is empty.     if not root:         return        q = deque()      # Start BFS with the root node.     q.append(root)     lvl = 0      while q:         size = len(q)         cur = []          # Process all nodes at the current lvl.         for _ in range(size):             node = q.popleft()             cur.append(node)              if node.left: q.append(node.left)             if node.right: q.append(node.right)          # Reverse node values if the current lvl is odd.         if lvl % 2 == 1:             left, right = 0, len(cur) - 1             while left < right:                 cur[left].data, cur[right].data = \                     cur[right].data, cur[left].data                 left += 1                 right -= 1          lvl += 1  # A utility function to print inorder  # traversal of a binary tree def printInorder(root):     if root is None:         return     printInorder(root.left)     print(root.data, end=" ")     printInorder(root.right)  # Driver Code if __name__ == "__main__":     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)      print("Inorder Traversal of given tree")     printInorder(root)      reverseAlternate(root)      print("\nInorder Traversal of modified tree")     printInorder(root) 
C#
// C# program to reverse alternate  // levels of a binary tree  using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // The main function to reverse      // alternate nodes of a binary tree     static void reverseAlternate(Node root) {          // Return if the tree is empty.         if (root == null) {             return;         }          Queue<Node> q = new Queue<Node>();          // Start BFS with the root node.         q.Enqueue(root);         int lvl = 0;          while (q.Count > 0) {             int size = q.Count;             List<Node> cur = new List<Node>();              // Process all nodes at the current lvl.             for (int i = 0; i < size; i++) {                 Node node = q.Dequeue();                 cur.Add(node);                  if (node.left != null) q.Enqueue(node.left);                 if (node.right != null) q.Enqueue(node.right);             }              // Reverse node values if the current lvl is odd.             if (lvl % 2 == 1) {                 int left = 0, right = cur.Count - 1;                 while (left < right) {                     int temp = cur[left].data;                     cur[left].data = cur[right].data;                     cur[right].data = temp;                     left++;                     right--;                 }             }              lvl++;         }     }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         Console.Write(root.data + " ");         printInorder(root.right);     }      static void Main() {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          Console.WriteLine("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          Console.WriteLine("\nInorder Traversal of modified tree");         printInorder(root);     } } 
JavaScript
// JavaScript program to reverse alternate  // levels of a binary tree  class Node {     constructor(data) {         this.data = data;         this.left = this.right = null;     } }  // The main function to reverse  // alternate nodes of a binary tree function reverseAlternate(root) {      // Return if the tree is empty.     if (!root) {         return;       }      let q = [];      // Start BFS with the root node.     q.push(root);     let lvl = 0;      while (q.length > 0) {         let size = q.length;         let cur = [];          // Process all nodes at the current lvl.         for (let i = 0; i < size; i++) {             let node = q.shift();             cur.push(node);              if (node.left) q.push(node.left);             if (node.right) q.push(node.right);         }          // Reverse node values if the current lvl is odd.         if (lvl % 2 === 1) {             let left = 0, right = cur.length - 1;             while (left < right) {                 [cur[left].data, cur[right].data] = [cur[right].data, cur[left].data];                 left++;                 right--;             }         }          lvl++;     } }  // A utility function to print inorder  // traversal of a binary tree function printInorder(root) {     if (root === null) return;     printInorder(root.left);     process.stdout.write(root.data + " ");     printInorder(root.right); }  // Driver Code let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7);  console.log("Inorder Traversal of given tree"); printInorder(root);  reverseAlternate(root);  console.log("\nInorder Traversal of modified tree"); printInorder(root); 

Output
Inorder Traversal of given tree 4 2 5 1 6 3 7  Inorder Traversal of modified tree 4 3 5 1 6 2 7 

Time Complexity: O(n), as it does level order traversal of the binary tree.
Space Complexity: O(n), to store the nodes in queue and array.

[Expected Approach] – Using Preorder Traversal – O(n) Time and O(log n) Space

The idea is to use Preorder Traversal and for nodes at even levels, we swap the values at their left and right child nodes to reverse the arrangement of nodes below their level, while leaving the children of odd levels unchanged. To do so, if current level is even, swap the values rooted at left and right child, and recur for the next even level. If any of the node is empty, stop the recursion.

Below is given the implementation:

C++
// C++ program to reverse alternate  // levels of a binary tree #include<bits/stdc++.h> using namespace std;  // A Binary Tree node class Node {     public:     int data;     Node *left, *right;     Node(int data) {         this->data = data;         this->left = this->right = nullptr;     } };  // to perform preorder traversal of the tree and // modify the binary tree void preorder(struct Node *a, struct Node *b, int lvl) {      // Base cases     if (a == nullptr || b == nullptr)         return;      // Swap subtrees if level is even     if (lvl % 2 == 0)         swap(a->data, b->data);      // Recur for left and right subtrees     preorder(a->left, b->right, lvl + 1);     preorder(a->right, b->left, lvl + 1); }  void reverseAlternate(struct Node *root) {      preorder(root->left, root->right, 0);  }  // A utility function to print indorder  // traversal of a binary tree void printInorder(struct Node *root) {     if (root == nullptr) return;     printInorder(root->left);     cout << root->data << " ";     printInorder(root->right); }  int main() {     Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);     root->right->right = new Node(7);      cout << "Inorder Traversal of given tree\n";     printInorder(root);      reverseAlternate(root);      cout << "\nInorder Traversal of modified tree\n";     printInorder(root);      return 0; } 
Java
// Java program to reverse alternate  // levels of a binary tree  class Node {     int data;     Node left, right;      Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // to perform preorder traversal of the tree and     // modify the binary tree     static void preorder(Node a, Node b, int lvl) {          // Base cases         if (a == null || b == null)             return;          // Swap subtrees if level is even         if (lvl % 2 == 0) {             int temp = a.data;             a.data = b.data;             b.data = temp;         }          // Recur for left and right subtrees         preorder(a.left, b.right, lvl + 1);         preorder(a.right, b.left, lvl + 1);     }      static void reverseAlternate(Node root) {          preorder(root.left, root.right, 0);      }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         System.out.print(root.data + " ");         printInorder(root.right);     }      public static void main(String[] args) {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          System.out.println("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          System.out.println("\nInorder Traversal of modified tree");         printInorder(root);     } } 
Python
# Python program to reverse alternate  # levels of a binary tree  class Node:     def __init__(self, data):         self.data = data         self.left = self.right = None  # to perform preorder traversal of the tree and # modify the binary tree def preorder(a, b, lvl):      # Base cases     if a is None or b is None:         return      # Swap subtrees if level is even     if lvl % 2 == 0:         a.data, b.data = b.data, a.data      # Recur for left and right subtrees     preorder(a.left, b.right, lvl + 1)     preorder(a.right, b.left, lvl + 1)  def reverseAlternate(root):      preorder(root.left, root.right, 0)   # A utility function to print inorder  # traversal of a binary tree def printInorder(root):     if root is None:         return     printInorder(root.left)     print(root.data, end=" ")     printInorder(root.right)  # Driver Code if __name__ == "__main__":     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)      print("Inorder Traversal of given tree")     printInorder(root)      reverseAlternate(root)      print("\nInorder Traversal of modified tree")     printInorder(root) 
C#
// C# program to reverse alternate  // levels of a binary tree  using System;  class Node {     public int data;     public Node left, right;      public Node(int data) {         this.data = data;         this.left = this.right = null;     } }  class GFG {      // to perform preorder traversal of the tree and     // modify the binary tree     static void preorder(Node a, Node b, int lvl) {          // Base cases         if (a == null || b == null)             return;          // Swap subtrees if level is even         if (lvl % 2 == 0) {             int temp = a.data;             a.data = b.data;             b.data = temp;         }          // Recur for left and right subtrees         preorder(a.left, b.right, lvl + 1);         preorder(a.right, b.left, lvl + 1);     }      static void reverseAlternate(Node root) {          preorder(root.left, root.right, 0);      }      // A utility function to print inorder      // traversal of a binary tree     static void printInorder(Node root) {         if (root == null) return;         printInorder(root.left);         Console.Write(root.data + " ");         printInorder(root.right);     }      static void Main() {         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          Console.WriteLine("Inorder Traversal of given tree");         printInorder(root);          reverseAlternate(root);          Console.WriteLine("\nInorder Traversal of modified tree");         printInorder(root);     } } 
JavaScript
// JavaScript program to reverse alternate  // levels of a binary tree  class Node {     constructor(data) {         this.data = data;         this.left = this.right = null;     } }  // to perform preorder traversal of the tree and // modify the binary tree function preorder(a, b, lvl) {      // Base cases     if (a === null || b === null)         return;      // Swap subtrees if level is even     if (lvl % 2 === 0) {         let temp = a.data;         a.data = b.data;         b.data = temp;     }      // Recur for left and right subtrees     preorder(a.left, b.right, lvl + 1);     preorder(a.right, b.left, lvl + 1); }  function reverseAlternate(root) {      preorder(root.left, root.right, 0);  }  // A utility function to print inorder  // traversal of a binary tree function printInorder(root) {     if (root === null) return;     printInorder(root.left);     process.stdout.write(root.data + " ");     printInorder(root.right); }  // Driver Code let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7);  console.log("Inorder Traversal of given tree"); printInorder(root);  reverseAlternate(root);  console.log("\nInorder Traversal of modified tree"); printInorder(root); 

Output
Inorder Traversal of given tree 4 2 5 1 6 3 7  Inorder Traversal of modified tree 4 3 5 1 6 2 7 

Time Complexity: O(n), as we are traversing the tree once.
Auxiliary Space: O(log n), considering the recursive call stack, where log(n) is the height of the perfect binary tree.



Next Article
Reverse alternate levels of a perfect binary tree using Stack
author
kartik
Improve
Article Tags :
  • DSA
  • Tree
  • Amazon
  • Hike
  • Reverse
Practice Tags :
  • Amazon
  • Hike
  • Reverse
  • Tree

Similar Reads

  • Reverse alternate levels of a perfect binary tree using Stack
    Given a Perfect Binary Tree, the task is to reverse the alternate level nodes of the binary tree.Examples: Input: a / \ b c / \ / \ d e f g / \ / \ / \ / \ h i j k l m n o Output: Inorder Traversal of given tree h d i b j e k a l f m c n g o Inorder Traversal of modified tree o d n c m e l a k f j b
    10 min read
  • Print alternate nodes from all levels of a Binary Tree
    Given a binary tree, the task is to traverse each level of the given binary tree from left to right and print every alternate encountered at a level. Examples: Input: Output: 1 2 3 9 5 7 Input: Output: 71 88 4 6 8 10 13 Approach: The problem can be solved by performing Level Order Traversal traversa
    6 min read
  • Boundary Level order traversal of a Binary Tree
    Given a Binary Tree, the task is to print all levels of this tree in Boundary Level order traversal. Boundary Level order traversal: In this traversal, the first element of the level (starting boundary) is printed first, followed by last element (ending boundary). Then the process is repeated for th
    11 min read
  • Print all Palindromic Levels Of a Binary Tree
    Given a Binary Tree, the task is to print all palindromic levels of this tree. Palindrome Level Any level of a Binary tree is said to be a palindromic level if on traversing it from left to right, the result is same as traversing that level from right to left. Examples: Input: 1 / \ 12 13 / / \ 11 6
    11 min read
  • Perfect Binary Tree Specific Level Order Traversal
    Given a Perfect Binary Tree like below: Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels
    15+ min read
  • Print Levels of all nodes in a Binary Tree
    Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
    7 min read
  • Specific Level Order Traversal of Binary Tree
    Given a Binary Tree, the task is to perform a Specific Level Order Traversal of the tree such that at each level print 1st element then the last element, then 2nd element and 2nd last element, until all elements of that level are printed and so on. Examples: Input: Output: 5 3 7 2 8 4 6 9 0 5 1 Expl
    8 min read
  • Anti Clockwise spiral traversal of a binary tree
    Given a binary tree, the task is to print the nodes of the tree in an anti-clockwise spiral manner. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 1 4 5 6 7 3 2 Input: 1 / \ 2 3 / / \ 4 5 6 / \ / / \ 7 8 9 10 11 Output: 1 7 8 9 10 11 3 2 4 5 6 Approach: The idea is to use two variables i initial
    15+ min read
  • Perfect Binary Tree Specific Level Order Traversal | Set 2
    Perfect Binary Tree using Specific Level Order Traversal in Set 1. The earlier traversal was from Top to Bottom. In this post, Bottom to Top traversal (asked in Amazon Interview | Set 120 – Round 1) is discussed. 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 8 15 9 14 10 13 11 12 4 7 5 6 2 3 1The
    15+ min read
  • Sum of all vertical levels of a Binary Tree
    Given a binary tree consisting of either 1 or 0 as its node values, the task is to find the sum of all vertical levels of the Binary Tree, considering each value to be a binary representation. Examples: Input: 1 / \ 1 0 / \ / \ 1 0 1 0Output: 7Explanation: Taking vertical levels from left to right:F
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences