SlideShare a Scribd company logo
1 of 4
Download to read offline
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

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

Array
ArrayArray
Array
 
Unit - 2.pdf
Unit - 2.pdfUnit - 2.pdf
Unit - 2.pdf
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithms
 
Leftlist Heap-1.pdf
Leftlist Heap-1.pdfLeftlist Heap-1.pdf
Leftlist Heap-1.pdf
 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
 
Trees in data structrures
Trees in data structruresTrees in data structrures
Trees in data structrures
 
Java code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdfJava code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdf
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
Trees
TreesTrees
Trees
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Unit III Heaps.ppt
Unit III Heaps.pptUnit III Heaps.ppt
Unit III Heaps.ppt
 
Binary Tree
Binary  TreeBinary  Tree
Binary Tree
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 
3.linked list
3.linked list3.linked list
3.linked list
 
Data Structure
Data StructureData Structure
Data Structure
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
Heaps & Adaptable priority Queues
Heaps & Adaptable priority QueuesHeaps & Adaptable priority Queues
Heaps & Adaptable priority Queues
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Bcsl 033 solve assignment
Bcsl 033 solve assignmentBcsl 033 solve assignment
Bcsl 033 solve assignment
 

More from funkybabyindia

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

More from funkybabyindia (20)

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

Recently uploaded

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Recently uploaded (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

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; }