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:
Level order traversal of Binary Tree using Morris Traversal
Next article icon

Reverse alternate levels of a perfect binary tree using Stack

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 i g h  Input:                a               / \              b   c Output: Inorder Traversal of given tree b a c  Inorder Traversal of modified tree c a b

Approach: Another approach to the problem is discussed here. In this article, we discuss an approach involving stack. 
Traverse the tree in a depth-first fashion and for each level, 

  • If the level is odd, push the left and right child(if exists) in a stack.
  • If the level is even, replace the value of the current node with the top of the stack.

Below is the implementation of the above approach: 
 

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // A tree node struct Node {     char key;     struct Node *left, *right; };  // Utility function to create new Node Node* newNode(int key) {     Node* temp = new Node;     temp->key = key;     temp->left = temp->right = NULL;     return (temp); }  // Utility function to perform // inorder traversal of the tree void inorder(Node* root) {     if (root != NULL) {         inorder(root->left);         cout << root->key << " ";         inorder(root->right);     } }  // Function to reverse alternate nodes void reverseAlternate(Node* root) {      // Queue for depth first traversal     queue<Node*> q;     q.push(root);     Node* temp;      // Level of root considered to be 1     int n, level = 1;      // Stack to store nodes of a level     stack<int> s;      while (!q.empty()) {         n = q.size();         while (n--) {             temp = q.front();             q.pop();              // If level is odd             if (level % 2) {                  // Store the left and right child                 // in the stack                 if (temp->left) {                     q.push(temp->left);                     s.push(temp->left->key);                 }                  if (temp->right) {                     q.push(temp->right);                     s.push(temp->right->key);                 }             }              // If level is even             else {                  // Replace the value of node                 // with top of the stack                 temp->key = s.top();                 s.pop();                  if (temp->left)                     q.push(temp->left);                 if (temp->right)                     q.push(temp->right);             }         }          // Increment the level         level++;     } }  // Driver code int main() {     struct Node* root = newNode('a');     root->left = newNode('b');     root->right = newNode('c');     root->left->left = newNode('d');     root->left->right = newNode('e');     root->right->left = newNode('f');     root->right->right = newNode('g');     root->left->left->left = newNode('h');     root->left->left->right = newNode('i');     root->left->right->left = newNode('j');     root->left->right->right = newNode('k');     root->right->left->left = newNode('l');     root->right->left->right = newNode('m');     root->right->right->left = newNode('n');     root->right->right->right = newNode('o');      cout << "Inorder Traversal of given tree\n";     inorder(root);      reverseAlternate(root);      cout << "\nInorder Traversal of modified tree\n";     inorder(root);      return 0; } 
Java
// Java implementation of the approach  import java.util.*;  class GfG {   // A tree node  static class Node {      char key;      Node left, right;  }  // Utility function to create new Node  static Node newNode(char key)  {      Node temp = new Node();      temp.key = key;      temp.left = temp.right = null;      return (temp);  }   // Utility function to perform  // inorder traversal of the tree  static void inorder(Node root)  {      if (root != null)     {          inorder(root.left);          System.out.print(root.key + " ");          inorder(root.right);      }  }   // Function to reverse alternate nodes  static void reverseAlternate(Node root)  {       // Queue for depth first traversal      Queue<Node> q = new LinkedList<Node> ();      q.add(root);      Node temp;       // Level of root considered to be 1      int n, level = 1;       // Stack to store nodes of a level      Stack<Character> s = new Stack<Character> ();       while (!q.isEmpty())     {          n = q.size();          while (n != 0)         {              if(!q.isEmpty())              {                 temp = q.peek();                  q.remove();              }             else             temp = null;                          // If level is odd              if (level % 2 != 0)             {                   // Store the left and right child                  // in the stack                  if (temp != null && temp.left != null)                  {                      q.add(temp.left);                      s.push(temp.left.key);                  }                   if (temp != null && temp.right != null)                 {                      q.add(temp.right);                      s.push(temp.right.key);                  }              }               // If level is even              else             {                   // Replace the value of node                  // with top of the stack                  temp.key = s.peek();                  s.pop();                   if (temp.left != null)                      q.add(temp.left);                  if (temp.right != null)                      q.add(temp.right);              }             n--;         }           // Increment the level          level++;      }  }   // Driver code  public static void main(String[] args)  {      Node root = newNode('a');      root.left = newNode('b');      root.right = newNode('c');      root.left.left = newNode('d');      root.left.right = newNode('e');      root.right.left = newNode('f');      root.right.right = newNode('g');      root.left.left.left = newNode('h');      root.left.left.right = newNode('i');      root.left.right.left = newNode('j');      root.left.right.right = newNode('k');      root.right.left.left = newNode('l');      root.right.left.right = newNode('m');      root.right.right.left = newNode('n');      root.right.right.right = newNode('o');       System.out.println("Inorder Traversal of given tree");      inorder(root);       reverseAlternate(root);       System.out.println("\nInorder Traversal of modified tree");      inorder(root);  } }   // This code is contributed by Prerna Saini 
Python3
# Python3 implementation of the  # above approach  # A tree node class Node:          def __init__(self, key):                self.key = key         self.left = None         self.right = None      # Utility function to # create new Node def newNode(key):      temp = Node(key)     return temp  # Utility function to perform # inorder traversal of the tree def inorder(root):      if (root != None):         inorder(root.left);         print(root.key,               end = ' ')         inorder(root.right);      # Function to reverse  # alternate nodes def reverseAlternate(root):       # Queue for depth      # first traversal     q = []     q.append(root);          temp = None       # Level of root considered      # to be 1     n = 0     level = 1;       # Stack to store nodes      # of a level     s = []       while (len(q) != 0):                 n = len(q);                 while (n != 0):                         n -= 1             temp = q[0];             q.pop(0);               # If level is odd             if (level % 2 != 0):                   # Store the left and                  # right child in the stack                 if (temp.left != None):                     q.append(temp.left);                     s.append(temp.left.key);                                    if (temp.right != None):                     q.append(temp.right);                     s.append(temp.right.key);               # If level is even             else:                   # Replace the value of node                 # with top of the stack                 temp.key = s[-1];                 s.pop();                   if (temp.left != None):                     q.append(temp.left);                 if (temp.right != None):                     q.append(temp.right);           # Increment the level         level += 1;      # Driver code if __name__ == "__main__":          root = newNode('a');     root.left = newNode('b');     root.right = newNode('c');     root.left.left = newNode('d');     root.left.right = newNode('e');     root.right.left = newNode('f');     root.right.right = newNode('g');     root.left.left.left = newNode('h');     root.left.left.right = newNode('i');     root.left.right.left = newNode('j');     root.left.right.right = newNode('k');     root.right.left.left = newNode('l');     root.right.left.right = newNode('m');     root.right.right.left = newNode('n');     root.right.right.right = newNode('o');          print("Inorder Traversal of given tree")     inorder(root);       reverseAlternate(root);          print("\nInorder Traversal of modified tree")     inorder(root);      # This code is contributed by Rutvik_56 
C#
// C# implementation of the approach  using System; using System.Collections;  class GfG  {   // A tree node  public class Node  {      public char key;      public Node left, right;  }   // Utility function to create new Node  static Node newNode(char key)  {      Node temp = new Node();      temp.key = key;      temp.left = temp.right = null;      return (temp);  }   // Utility function to perform  // inorder traversal of the tree  static void inorder(Node root)  {      if (root != null)      {          inorder(root.left);          Console.Write(root.key + " ");          inorder(root.right);      }  }   // Function to reverse alternate nodes  static void reverseAlternate(Node root)  {       // Queue for depth first traversal      Queue q = new Queue ();      q.Enqueue(root);      Node temp;       // Level of root considered to be 1      int n, level = 1;       // Stack to store nodes of a level      Stack s = new Stack ();       while (q.Count > 0)      {          n = q.Count;          while (n != 0)          {              if(q.Count > 0)              {                  temp = (Node)q.Peek();                  q.Dequeue();              }              else             temp = null;                           // If level is odd              if (level % 2 != 0)              {                   // Store the left and right child                  // in the stack                  if (temp != null && temp.left != null)                  {                      q.Enqueue(temp.left);                      s.Push(temp.left.key);                  }                   if (temp != null && temp.right != null)                  {                      q.Enqueue(temp.right);                      s.Push(temp.right.key);                  }              }               // If level is even              else             {                   // Replace the value of node                  // with top of the stack                  temp.key =(char)s.Peek();                  s.Pop();                   if (temp.left != null)                      q.Enqueue(temp.left);                  if (temp.right != null)                      q.Enqueue(temp.right);              }              n--;          }           // Increment the level          level++;      }  }   // Driver code  public static void Main(String []args)  {      Node root = newNode('a');      root.left = newNode('b');      root.right = newNode('c');      root.left.left = newNode('d');      root.left.right = newNode('e');      root.right.left = newNode('f');      root.right.right = newNode('g');      root.left.left.left = newNode('h');      root.left.left.right = newNode('i');      root.left.right.left = newNode('j');      root.left.right.right = newNode('k');      root.right.left.left = newNode('l');      root.right.left.right = newNode('m');      root.right.right.left = newNode('n');      root.right.right.right = newNode('o');       Console.WriteLine("Inorder Traversal of given tree");      inorder(root);       reverseAlternate(root);       Console.WriteLine("\nInorder Traversal of modified tree");      inorder(root);  }  }   // This code is contributed by Arnab Kundu 
JavaScript
<script>  // JavaScript implementation of the approach   // A tree node  class Node  {      constructor()     {         this.key = '';         this.left = null;         this.right = null;     } }   // Utility function to create new Node  function newNode(key)  {      var temp = new Node();      temp.key = key;      temp.left = temp.right = null;      return (temp);  }   // Utility function to perform  // inorder traversal of the tree  function inorder(root)  {      if (root != null)      {          inorder(root.left);          document.write(root.key + " ");          inorder(root.right);      }  }   // Function to reverse alternate nodes  function reverseAlternate(root)  {       // Queue for depth first traversal      var q = [];      q.push(root);      var temp = null;       // Level of root considered to be 1      var n, level = 1;       // Stack to store nodes of a level      var s = [];      while (q.length > 0)      {          n = q.length;          while (n != 0)          {              if(q.length > 0)              {                  temp = q[0];                  q.shift();              }              else             temp = null;                           // If level is odd              if (level % 2 != 0)              {                   // Store the left and right child                  // in the stack                  if (temp != null && temp.left != null)                  {                      q.push(temp.left);                      s.push(temp.left.key);                  }                   if (temp != null && temp.right != null)                  {                      q.push(temp.right);                      s.push(temp.right.key);                  }              }               // If level is even              else             {                   // Replace the value of node                  // with top of the stack                  temp.key = s[s.length-1];                  s.pop();                   if (temp.left != null)                      q.push(temp.left);                  if (temp.right != null)                      q.push(temp.right);              }              n--;          }           // Increment the level          level++;      }  }   // Driver code  var root = newNode('a');  root.left = newNode('b');  root.right = newNode('c');  root.left.left = newNode('d');  root.left.right = newNode('e');  root.right.left = newNode('f');  root.right.right = newNode('g');  root.left.left.left = newNode('h');  root.left.left.right = newNode('i');  root.left.right.left = newNode('j');  root.left.right.right = newNode('k');  root.right.left.left = newNode('l');  root.right.left.right = newNode('m');  root.right.right.left = newNode('n');  root.right.right.right = newNode('o');  document.write("Inorder Traversal of given tree<br>");  inorder(root);  reverseAlternate(root);  document.write("<br>Inorder Traversal of modified tree<br>");  inorder(root);   </script> 

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 i g h

 

The time complexity of the above approach is O(N) where N is the number of nodes in the tree as we are traversing through all the nodes once.

The space complexity of the above approach is O(N) as we are using a queue and a stack which can store up to N elements.


Next Article
Level order traversal of Binary Tree using Morris Traversal
author
sajal10798
Improve
Article Tags :
  • Tree
  • DSA
Practice Tags :
  • Tree

Similar Reads

  • Reverse alternate levels of a perfect binary tree
    Given a perfect binary tree, your task is to reverse the nodes present at alternate levels. Examples: Input: root = [1, 3, 2] 1 / \ 3 2Output: 1 / \ 2 3Explanation: Nodes at level 2 are reversed. Input: root = [1, 2, 3, 4, 5, 6, 7] 1 / \ 2 3 / \ / \ 4 5 6 7Output: 1 / \ 3 2 / \ / \ 4 5 6 7Explanatio
    15+ min read
  • Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
    Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965};Output : 290 530 965Explanation: Below is the representation of BST using preorder array. Approach: To i
    8 min read
  • Print Binary Tree levels in sorted order | Set 2 (Using set)
    Given a tree, print the level order traversal in sorted order. Examples : Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 7 5 6 1 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output : 7 1 16 4 13 We have discussed a priority queue based solution in below post.Print Binary Tree levels in sorted order | Set 1 (Using
    5 min read
  • Level order traversal of Binary Tree using Morris Traversal
    Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two ob
    11 min read
  • Density of Binary Tree using Level Order Traversal
    Given a Binary Tree, the task is to find the density of it by doing one traversal of it. Density of Binary Tree = Size / Height. Examples: Input: Output: 1.5Explanation: As the height of given tree is 2 and size of given tree is 3 , the density is (3/2) = 1.5 Input: Output: 1Explanation: As the heig
    5 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
  • Left View of a Binary Tree Using Stack
    Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level. Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. Example 2: The Green colored nodes represents the le
    8 min read
  • Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
    Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5
    13 min read
  • Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
    Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bo
    15+ 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
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