
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Mirror of n-ary Tree in C++
Problem statement
Given a Tree where every node contains variable number of children, convert the tree to its mirror
Example
If n-ary tree is −
Then it’s mirror is −
Example
#include <bits/stdc++.h> using namespace std; struct node { int data; vector<node *>child; }; node *newNode(int x) { node *temp = new node; temp->data = x; return temp; } void mirrorTree(node * root) { if (root == NULL) { return; } int n = root->child.size(); if (n < 2) { return; } for (int i = 0; i < n; i++) { mirrorTree(root->child[i]); } reverse(root->child.begin(), root->child.end()); } void printTree(node * root) { if (root == NULL) { return; } queue<node *>q; q.push(root); int level = 0; while (!q.empty()) { int n = q.size(); ++level; cout << "Level " << level << ": "; while (n > 0) { node * p = q.front(); q.pop(); cout << p->data << " "; for (int i=0; i<p->child.size(); i++) { q.push(p->child[i]); } n--; } cout << endl; } } int main() { node *root = newNode(20); (root->child).push_back(newNode(10)); (root->child).push_back(newNode(15)); (root->child[0]->child).push_back(newNode(1)); (root->child[0]->child).push_back(newNode(2)); (root->child[0]->child).push_back(newNode(3)); (root->child[1]->child).push_back(newNode(4)); cout << "Tree traversal before mirroring\n"; printTree(root); mirrorTree(root); cout << "\nTree traversal after mirroring\n"; printTree(root); return 0; }
When you compile and execute above program. It generates following output −
Output
Tree traversal before mirroring Level 1: 20 Level 2: 10 15 Level 3: 1 2 3 4 Tree traversal after mirroring Level 1: 20 Level 2: 15 10 Level 3: 4 3 2 1
- Related Articles
- Depth of an N-Ary tree in C++?
- Encode N-ary Tree to Binary Tree in C++
- N-ary Tree Preorder Traversal in C++
- Depth of an N-Ary tree in C++ Program
- N-ary Tree Level Order Traversal in C++
- Serialize and Deserialize N-ary Tree in C++
- Preorder Traversal of N-ary Tree Without Recursion in C++
- Even size subtree in n-ary tree in C++
- Next Larger element in n-ary tree in C++
- Print all leaf nodes of an n-ary tree using DFS in C++
- Number of nodes greater than a given value in n-ary tree in C++
- Find the Number of Siblings of a Given Node in N-ary Tree using C++
- Find the Number of Ways to Traverse an N-ary Tree using C++
- Number of leaf nodes in the subtree of every node of an n-ary tree in C++
- m-ary tree

Advertisements