Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Reverse a path in BST using queue
Next article icon

Reverse a path in BST using queue

Last Updated : 17 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary search tree and a key, your task to reverse path of the binary tree.

Prerequisite : Reverse path of Binary tree

Examples : 

Input :       50            /     \           30      70          /  \    /  \        20   40  60   80  k = 70 Output : Inorder before reversal : 20 30 40 50 60 70 80  Inorder after reversal : 20 30 40 70 60 50 80   Input :       8            /     \           3       10          /  \       \        1    6         14            /  \      /           4    7    13 k = 13 Output : Inorder before reversal : 1 3 4 6 7 8 10 13 14 Inorder after reversal : 1 3 4 6 7 13 14 8 10

Approach: Take a queue and push all the element till that given key at the end replace node key with queue front element till root, then print inorder of the tree.

Below is the implementation of above approach :  

C++
// C++ code to demonstrate insert // operation in binary search tree #include <bits/stdc++.h> using namespace std;  struct node {     int key;     struct node *left, *right; };  // A utility function to  // create a new BST node struct node* newNode(int item) {     struct node* temp = new node;     temp->key = item;     temp->left = temp->right = NULL;     return temp; }  // A utility function to  // do inorder traversal of BST void inorder(struct node* root) {     if (root != NULL) {         inorder(root->left);         cout << root->key << " ";         inorder(root->right);     } }  // reverse tree path using queue void reversePath(struct node** node,             int& key, queue<int>& q1) {     /* If the tree is empty,      return a new node */     if (node == NULL)         return;      // If the node key equal     // to key then     if ((*node)->key == key)      {         // push current node key         q1.push((*node)->key);          // replace first node         // with last element         (*node)->key = q1.front();          // remove first element         q1.pop();          // return         return;     }          // if key smaller than node key then     else if (key < (*node)->key)     {         // push node key into queue         q1.push((*node)->key);          // recursive call itself         reversePath(&(*node)->left, key, q1);          // replace queue front to node key         (*node)->key = q1.front();          // perform pop in queue         q1.pop();     }          // if key greater than node key then     else if (key > (*node)->key)     {         // push node key into queue         q1.push((*node)->key);          // recursive call itself         reversePath(&(*node)->right, key, q1);          // replace queue front to node key         (*node)->key = q1.front();          // perform pop in queue         q1.pop();     }      // return     return; }  /* A utility function to insert a new node with given key in BST */ struct node* insert(struct node* node,                               int key) {     /* If the tree is empty,     return a new node */     if (node == NULL)         return newNode(key);      /* Otherwise, recur down the tree */     if (key < node->key)         node->left = insert(node->left, key);     else if (key > node->key)         node->right = insert(node->right, key);      /* return the (unchanged) node pointer */     return node; }  // Driver Program to test above functions int main() {     /* Let us create following BST               50            /     \           30      70          /  \    /  \        20   40  60   80 */     struct node* root = NULL;     queue<int> q1;      // reverse path till k     int k = 80;     root = insert(root, 50);     insert(root, 30);     insert(root, 20);     insert(root, 40);     insert(root, 70);     insert(root, 60);     insert(root, 80);      cout << "Before Reverse :" << endl;     // print inorder traversal of the BST     inorder(root);      cout << "\n";      // reverse path till k     reversePath(&root, k, q1);          cout << "After Reverse :" << endl;      // print inorder of reverse path tree     inorder(root);      return 0; } 
Java
// Java code to demonstrate insert // operation in binary search tree import java.util.*; class GFG {   static class node    {     int key;     node left, right;   };   static node root = null;   static Queue<Integer> q1;   static int k;    // A utility function to   // create a new BST node   static node newNode(int item)   {     node temp = new node();     temp.key = item;     temp.left = temp.right = null;     return temp;   }    // A utility function to   // do inorder traversal of BST   static void inorder(node root)   {     if (root != null)     {       inorder(root.left);       System.out.print(root.key + " ");       inorder(root.right);     }   }    // reverse tree path using queue   static void reversePath(node node)   {      /* If the tree is empty,         return a new node */     if (node == null)       return;      // If the node key equal     // to key then     if ((node).key == k)     {        // push current node key       q1.add((node).key);        // replace first node       // with last element       (node).key = q1.peek();        // remove first element       q1.remove();        // return       return;     }      // if key smaller than node key then     else if (k < (node).key)      {        // push node key into queue       q1.add((node).key);        // recursive call itself       reversePath((node).left);        // replace queue front to node key       (node).key = q1.peek();        // perform pop in queue       q1.remove();     }      // if key greater than node key then     else if (k > (node).key)     {        // push node key into queue       q1.add((node).key);        // recursive call itself       reversePath((node).right);        // replace queue front to node key       (node).key = q1.peek();        // perform pop in queue       q1.remove();     }      // return     return;   }    /* A utility function to insert     a new node with given key in BST */   static node insert(node node, int key)   {      /* If the tree is empty,         return a new node */     if (node == null)       return newNode(key);      /* Otherwise, recur down the tree */     if (key < node.key)       node.left = insert(node.left, key);     else if (key > node.key)       node.right = insert(node.right, key);      /* return the (unchanged) node pointer */     return node;   }    // Driver code   public static void main(String[] args)   {      /* Let us create following BST                   50                /     \               30      70              /  \    /  \            20   40  60   80 */     q1 = new LinkedList<>();      // reverse path till k     k = 80;     root = insert(root, 50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);     System.out.print("Before Reverse :"                      + "\n");     // print inorder traversal of the BST     inorder(root);     System.out.print("\n");      // reverse path till k     reversePath(root);     System.out.print("After Reverse :"                      + "\n");      // print inorder of reverse path tree     inorder(root);   } }  // This code is contributed by gauravrajput1 
Python3
# Python3 code to demonstrate insert  # operation in binary search tree  class Node:       # Constructor to create a new node      def __init__(self, data):          self.key = data          self.left = None         self.right = None  # A utility function to  # do inorder traversal of BST  def inorder(root):     if root != None:          inorder(root.left)          print(root.key, end = " ")          inorder(root.right)          # reverse tree path using queue  def reversePath(node, key, q1):          # If the tree is empty,      # return a new node */     if node == None:          return      # If the node key equal      # to key then      if node.key == key:                   # push current node key          q1.insert(0, node.key)           # replace first node          # with last element          node.key = q1[-1]           # remove first element          q1.pop()          # return          return          # if key smaller than node key then      elif key < node.key:                   # push node key into queue          q1.insert(0, node.key)           # recursive call itself          reversePath(node.left, key, q1)           # replace queue front to node key          node.key = q1[-1]           # perform pop in queue          q1.pop()          # if key greater than node key then      elif (key > node.key):                  # push node key into queue          q1.insert(0, node.key)           # recursive call itself          reversePath(node.right, key, q1)          # replace queue front to node key          node.key = q1[-1]          # perform pop in queue          q1.pop()      # return     return      # A utility function to insert  #a new node with given key in BST */ def insert(node, key):          # If the tree is empty,      # return a new node */     if node == None:         return Node(key)       # Otherwise, recur down the tree */     if key < node.key:         node.left = insert(node.left, key)     elif key > node.key:         node.right = insert(node.right, key)       # return the (unchanged) node pointer */     return node      # Driver Code if __name__ == '__main__':          # Let us create following BST      #             50      #         /     \      #         30     70      #         / \ / \      #     20 40 60 80 */     root = None     q1 = []       # reverse path till k      k = 80;      root = insert(root, 50)      insert(root, 30)     insert(root, 20)      insert(root, 40)      insert(root, 70)      insert(root, 60)      insert(root, 80)       print("Before Reverse :")           # print inorder traversal of the BST      inorder(root)      # reverse path till k      reversePath(root, k, q1)     print()     print("After Reverse :")      # print inorder of reverse path tree      inorder(root)           # This code is contributed by PranchalK 
C#
// C# code to demonstrate insert // operation in binary search tree using System; using System.Collections.Generic;  class GFG{  public class node  {     public int key;     public node left, right; };  static node root = null; static Queue<int> q1; static int k;  // A utility function to // create a new BST node static node newNode(int item) {     node temp = new node();     temp.key = item;     temp.left = temp.right = null;     return temp; }  // A utility function to // do inorder traversal of BST static void inorder(node root) {     if (root != null)     {         inorder(root.left);         Console.Write(root.key + " ");         inorder(root.right);     } }  // Reverse tree path using queue static void reversePath(node node) {          // If the tree is empty,     // return a new node      if (node == null)         return;          // If the node key equal     // to key then     if ((node).key == k)     {                  // push current node key         q1.Enqueue((node).key);                  // replace first node         // with last element         (node).key = q1.Peek();                  // Remove first element         q1.Dequeue();                  // Return         return;     }          // If key smaller than node key then     else if (k < (node).key)      {                  // push node key into queue         q1.Enqueue((node).key);                  // Recursive call itself         reversePath((node).left);                  // Replace queue front to node key         (node).key = q1.Peek();                  // Perform pop in queue         q1.Dequeue();     }          // If key greater than node key then     else if (k > (node).key)     {                  // push node key into queue         q1.Enqueue((node).key);                  // Recursive call itself         reversePath((node).right);                  // Replace queue front to node key         (node).key = q1.Peek();                  // Perform pop in queue         q1.Dequeue();     }          // Return     return; }  // A utility function to insert // a new node with given key in BST  static node insert(node node, int key) {          // If the tree is empty,     // return a new node      if (node == null)         return newNode(key);          // Otherwise, recur down the tree      if (key < node.key)         node.left = insert(node.left, key);     else if (key > node.key)         node.right = insert(node.right, key);          // Return the (unchanged) node pointer      return node; }  // Driver code public static void Main(String[] args) {          /* Let us create following BST           50        /     \       30      70      /  \    /  \     20   40  60   80 */     q1 = new Queue<int>();          // Reverse path till k     k = 80;     root = insert(root, 50);     root = insert(root, 30);     root = insert(root, 20);     root = insert(root, 40);     root = insert(root, 70);     root = insert(root, 60);     root = insert(root, 80);     Console.Write("Before Reverse :" + "\n");          // Print inorder traversal of the BST     inorder(root);     Console.Write("\n");          // Reverse path till k     reversePath(root);     Console.Write("After Reverse :" + "\n");          // Print inorder of reverse path tree     inorder(root); } }  // This code is contributed by gauravrajput1 
JavaScript
<script>  // javascript code to demonstrate insert // operation in binary search tree  class node  {     constructor()     {         this.key = 0;         this.left = null;         this.right = null;     } };  var root = null; var q1 = []; var k = 0;  // A utility function to // create a new BST node function newNode(item) {     var temp = new node();     temp.key = item;     temp.left = temp.right = null;     return temp; }  // A utility function to // do inorder traversal of BST function inorder(root) {     if (root != null)     {         inorder(root.left);         document.write(root.key + " ");         inorder(root.right);     } }  // Reverse tree path using queue function reversePath(node) {          // If the tree is empty,     // return a new node      if (node == null)         return;          // If the node key equal     // to key then     if ((node).key == k)     {                  // push current node key         q1.push((node).key);                  // replace first node         // with last element         (node).key = q1[0];                  // Remove first element         q1.shift();                  // Return         return;     }          // If key smaller than node key then     else if (k < (node).key)      {                  // push node key into queue         q1.push((node).key);                  // Recursive call itself         reversePath((node).left);                  // Replace queue front to node key         (node).key = q1[0];                  // Perform pop in queue         q1.shift();     }          // If key greater than node key then     else if (k > (node).key)     {                  // push node key into queue         q1.push((node).key);                  // Recursive call itself         reversePath((node).right);                  // Replace queue front to node key         (node).key = q1[0];                  // Perform pop in queue         q1.shift();     }          // Return     return; }  // A utility function to insert // a new node with given key in BST  function insert(node, key) {          // If the tree is empty,     // return a new node      if (node == null)         return newNode(key);          // Otherwise, recur down the tree      if (key < node.key)         node.left = insert(node.left, key);     else if (key > node.key)         node.right = insert(node.right, key);          // Return the (unchanged) node pointer      return node; }  // Driver code  /* Let us create following BST       50    /     \   30      70  /  \    /  \ 20   40  60   80 */ q1 = [];  // Reverse path till k k = 80; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); document.write("Before Reverse :" + "<br>");  // Print inorder traversal of the BST inorder(root); document.write("<br>");  // Reverse path till k reversePath(root); document.write("After Reverse :" + "<br>");  // Print inorder of reverse path tree inorder(root);  // This code is contributed by itsok. </script>  

Output
Before Reverse : 20 30 40 50 60 70 80  After Reverse : 20 30 40 80 60 70 50 

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Next Article
Reverse a path in BST using queue

D

devanshuagarwal
Improve
Article Tags :
  • Misc
  • Queue
  • Binary Search Tree
  • DSA
  • cpp-queue
Practice Tags :
  • Binary Search Tree
  • Misc
  • Queue

Similar Reads

    Reverse a Stack using Queue
    Given a stack, the task is to reverse the stack using the queue data structure. Examples: Input: Stack: (Top to Bottom) [10 -> 20 -> 30 -> 40]Output: Stack: (Top to Bottom) [40 -> 30 -> 20 -> 10] Input: Stack: [6 -> 5 -> 4]Output: Stack: [4 -> 5 -> 6] Approach: The prob
    5 min read
    Reversing a Queue using another Queue
    Given a queue. The task is to reverse the queue using another empty queue. Examples: Input: queue[] = {1, 2, 3, 4, 5} Output: 5 4 3 2 1 Input: queue[] = {10, 20, 30, 40} Output: 40 30 20 10 Approach: Given a queue and an empty queue.The last element of the queue should be the first element of the ne
    5 min read
    Reversing a Queue
    You are given a queue Q, and your task is to reverse the elements of the queue. You are only allowed to use the following standard queue operations:enqueue(x): Add an item x to the rear of the queue.dequeue(): Remove an item from the front of the queue.empty(): Check if the queue is empty or not.Exa
    4 min read
    Reversing a queue using recursion
    Given a queue, reverse the elements of the queue using recursion. The task is to reverse the order of the elements in the queue and return the reversed queue.Standard operations allowed:enqueue(x): Adds an item x to the rear of the queue.dequeue(): Removes an item from the front of the queue.empty()
    4 min read
    Turn a Queue into a Priority Queue
    What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the dat
    9 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