SlideShare a Scribd company logo
C++ Program:
Recursive reversal of a tree.
[16] Write a method void TreeNode::reverse() (with wrapper void Tree::reverse() ) which
recursively reverses the tree.
Solution
Answer:-
1) Traverse the given tree in inorder fashion and store all odd level nodes in an auxiliary array.
For the above example given tree, contents of array become {h, i, b, j, k, l, m, c, n, o}
2) Reverse the array. The array now becomes {o, n, c, m, l, k, j, b, i, h}
3) Traverse the tree again inorder fashion. While traversing the tree, one by one take elements
from array and store elements from array to every odd level traversed node.
For the above example, we traverse ‘h’ first in above array and replace ‘h’ with ‘o’. Then we
traverse ‘i’ and replace it with n.
Program:-
// C++ program to reverse alternate levels of a binary tree
#include
#define MAX 100
using namespace std;
// A Binary Tree node
struct Node
{
char data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree Node
struct Node *newNode(char item)
{
struct Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Function to store nodes of alternate levels in an array
void storeAlternate(Node *root, char arr[], int *index, int l)
{
// Base case
if (root == NULL) return;
// Store elements of left subtree
storeAlternate(root->left, arr, index, l+1);
// Store this node only if this is a odd level node
if (l%2 != 0)
{
arr[*index] = root->data;
(*index)++;
}
// Store elements of right subtree
storeAlternate(root->right, arr, index, l+1);
}
// Function to modify Binary Tree (All odd level nodes are
// updated by taking elements from array in inorder fashion)
void modifyTree(Node *root, char arr[], int *index, int l)
{
// Base case
if (root == NULL) return;
// Update nodes in left subtree
modifyTree(root->left, arr, index, l+1);
// Update this node only if this is an odd level node
if (l%2 != 0)
{
root->data = arr[*index];
(*index)++;
}
// Update nodes in right subtree
modifyTree(root->right, arr, index, l+1);
}
// A utility function to reverse an array from index
// 0 to n-1
void reverse(char arr[], int n)
{
int l = 0, r = n-1;
while (l < r)
{
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++; r--;
}
}
// 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
char *arr = new char[MAX];
int index = 0;
// First store nodes of alternate levels
storeAlternate(root, arr, &index, 0);
// Reverse the array
reverse(arr, index);
// Update tree by taking elements from array
index = 0;
modifyTree(root, arr, &index, 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);
}
// Driver Program to test above functions
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 ";
printInorder(root);
reverseAlternate(root);
cout << "  Inorder Traversal of modified tree ";
printInorder(root);
return 0;
}

More Related Content

Similar to C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf (20)

PDF
Binary Trees
Sriram Raj
 
PDF
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
DOCX
C++ adt c++ implementations
Rex Mwamba
 
DOCX
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
festockton
 
PPT
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
PDF
Add these three functions to the class binaryTreeType (provided).W.pdf
indiaartz
 
PDF
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
PDF
Binary Tree
Vishal Gaur
 
PDF
Modify this code to do an Insert function for an AVL tree, instead o.pdf
fathimaoptical
 
PPT
C Language Unit-8
kasaragadda srinivasrao
 
DOCX
Data structure lab on practical computer science.docx
nishapatil20005
 
DOCX
Data Structure lab on a practical in computer science
nishapatil20005
 
PPT
computer notes - Data Structures - 15
ecomputernotes
 
DOCX
hw1.docxCS 211 Homework #1Please complete the homework problem.docx
wellesleyterresa
 
PPT
computer notes - Data Structures - 13
ecomputernotes
 
PPT
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
DOCX
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
DOCX
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
DOCX
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
DOCX
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Binary Trees
Sriram Raj
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
C++ adt c++ implementations
Rex Mwamba
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
festockton
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Add these three functions to the class binaryTreeType (provided).W.pdf
indiaartz
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
Binary Tree
Vishal Gaur
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
fathimaoptical
 
C Language Unit-8
kasaragadda srinivasrao
 
Data structure lab on practical computer science.docx
nishapatil20005
 
Data Structure lab on a practical in computer science
nishapatil20005
 
computer notes - Data Structures - 15
ecomputernotes
 
hw1.docxCS 211 Homework #1Please complete the homework problem.docx
wellesleyterresa
 
computer notes - Data Structures - 13
ecomputernotes
 
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 

More from funkybabyindia (20)

PDF
Part C AssessmentsAs you examined each specific connective tissue,.pdf
funkybabyindia
 
PDF
please answer in details12 A communication system consists of 13 a.pdf
funkybabyindia
 
PDF
Name the plant phylum that exhibit the follow characteristics Co.pdf
funkybabyindia
 
PDF
Individuals that express the disease sickle cell anemia are homozygo.pdf
funkybabyindia
 
PDF
I will provide my LinkedList from my last lab.LinkedList.cpp~~~~.pdf
funkybabyindia
 
PDF
Implementing a basic directory-tree structure that is derived from a.pdf
funkybabyindia
 
PDF
I need help summarizing a research article!! I need to summarize an .pdf
funkybabyindia
 
PDF
For the pedigree on the right, individuals affected with the genetic.pdf
funkybabyindia
 
PDF
How are the xylem and phloem arranged in a eudicot rootA. the xyl.pdf
funkybabyindia
 
PDF
Graph 1 Annual growth () of national output 25 20 15 15 10 0 So.pdf
funkybabyindia
 
PDF
Explain why Drosophila are often used as model organisms in the study.pdf
funkybabyindia
 
PDF
Examine the two animals in the photographs figure. Use all of the c.pdf
funkybabyindia
 
PDF
Assess the types of stakeholders involved in the development process.pdf
funkybabyindia
 
PDF
There is a well-defined classification s developed originally by Caro.pdf
funkybabyindia
 
PDF
Write the level of protein structure below each picture. A word bank .pdf
funkybabyindia
 
PDF
Why should assembly language be avoided for general application deve.pdf
funkybabyindia
 
PDF
Who was Jesus of Nazareth What was his message How did he convey t.pdf
funkybabyindia
 
PDF
why has America never been a homogenous societywhy has Amer.pdf
funkybabyindia
 
PDF
Which of these statements about Java are trueA.( T F ) Using va.pdf
funkybabyindia
 
PDF
When someone suffers from arteriosclerosis, there is a widening of th.pdf
funkybabyindia
 
Part C AssessmentsAs you examined each specific connective tissue,.pdf
funkybabyindia
 
please answer in details12 A communication system consists of 13 a.pdf
funkybabyindia
 
Name the plant phylum that exhibit the follow characteristics Co.pdf
funkybabyindia
 
Individuals that express the disease sickle cell anemia are homozygo.pdf
funkybabyindia
 
I will provide my LinkedList from my last lab.LinkedList.cpp~~~~.pdf
funkybabyindia
 
Implementing a basic directory-tree structure that is derived from a.pdf
funkybabyindia
 
I need help summarizing a research article!! I need to summarize an .pdf
funkybabyindia
 
For the pedigree on the right, individuals affected with the genetic.pdf
funkybabyindia
 
How are the xylem and phloem arranged in a eudicot rootA. the xyl.pdf
funkybabyindia
 
Graph 1 Annual growth () of national output 25 20 15 15 10 0 So.pdf
funkybabyindia
 
Explain why Drosophila are often used as model organisms in the study.pdf
funkybabyindia
 
Examine the two animals in the photographs figure. Use all of the c.pdf
funkybabyindia
 
Assess the types of stakeholders involved in the development process.pdf
funkybabyindia
 
There is a well-defined classification s developed originally by Caro.pdf
funkybabyindia
 
Write the level of protein structure below each picture. A word bank .pdf
funkybabyindia
 
Why should assembly language be avoided for general application deve.pdf
funkybabyindia
 
Who was Jesus of Nazareth What was his message How did he convey t.pdf
funkybabyindia
 
why has America never been a homogenous societywhy has Amer.pdf
funkybabyindia
 
Which of these statements about Java are trueA.( T F ) Using va.pdf
funkybabyindia
 
When someone suffers from arteriosclerosis, there is a widening of th.pdf
funkybabyindia
 

Recently uploaded (20)

PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PPTX
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
PPTX
Presentation: Climate Citizenship Digital Education
Karl Donert
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
Gall bladder, Small intestine and Large intestine.pptx
rekhapositivity
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
digestive system for Pharm d I year HAP
rekhapositivity
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
LEGAL ASPECTS OF PSYCHIATRUC NURSING.pptx
PoojaSen20
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
Presentation: Climate Citizenship Digital Education
Karl Donert
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
community health nursing question paper 2.pdf
Prince kumar
 
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
Explorando Recursos do Summer '25: Dicas Essenciais - 02
Mauricio Alexandre Silva
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
Gall bladder, Small intestine and Large intestine.pptx
rekhapositivity
 

C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf

  • 1. C++ Program: Recursive reversal of a tree. [16] Write a method void TreeNode::reverse() (with wrapper void Tree::reverse() ) which recursively reverses the tree. Solution Answer:- 1) Traverse the given tree in inorder fashion and store all odd level nodes in an auxiliary array. For the above example given tree, contents of array become {h, i, b, j, k, l, m, c, n, o} 2) Reverse the array. The array now becomes {o, n, c, m, l, k, j, b, i, h} 3) Traverse the tree again inorder fashion. While traversing the tree, one by one take elements from array and store elements from array to every odd level traversed node. For the above example, we traverse ‘h’ first in above array and replace ‘h’ with ‘o’. Then we traverse ‘i’ and replace it with n. Program:- // C++ program to reverse alternate levels of a binary tree #include #define MAX 100 using namespace std; // A Binary Tree node struct Node { char data; struct Node *left, *right; }; // A utility function to create a new Binary Tree Node struct Node *newNode(char item) { struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } // Function to store nodes of alternate levels in an array
  • 2. void storeAlternate(Node *root, char arr[], int *index, int l) { // Base case if (root == NULL) return; // Store elements of left subtree storeAlternate(root->left, arr, index, l+1); // Store this node only if this is a odd level node if (l%2 != 0) { arr[*index] = root->data; (*index)++; } // Store elements of right subtree storeAlternate(root->right, arr, index, l+1); } // Function to modify Binary Tree (All odd level nodes are // updated by taking elements from array in inorder fashion) void modifyTree(Node *root, char arr[], int *index, int l) { // Base case if (root == NULL) return; // Update nodes in left subtree modifyTree(root->left, arr, index, l+1); // Update this node only if this is an odd level node if (l%2 != 0) { root->data = arr[*index]; (*index)++; } // Update nodes in right subtree modifyTree(root->right, arr, index, l+1); } // A utility function to reverse an array from index // 0 to n-1 void reverse(char arr[], int n) {
  • 3. int l = 0, r = n-1; while (l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } // 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 char *arr = new char[MAX]; int index = 0; // First store nodes of alternate levels storeAlternate(root, arr, &index, 0); // Reverse the array reverse(arr, index); // Update tree by taking elements from array index = 0; modifyTree(root, arr, &index, 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); } // Driver Program to test above functions int main() { struct Node *root = newNode('a');
  • 4. 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 "; printInorder(root); reverseAlternate(root); cout << " Inorder Traversal of modified tree "; printInorder(root); return 0; }