在C ++中将二叉树转换为其镜像树
在本教程中,我们将讨论将二进制树转换为其镜像树的程序。
为此,我们将提供一个二叉树。我们的任务是交换左端和右端的值,从给定的二叉树创建一个镜像树。
示例
#include<bits/stdc++.h>
using namespace std;
//binary tree node structure
struct Node{
int data;
struct Node* left;
struct Node* right;
};
//creation of a new node with no child nodes
struct Node* newNode(int data){
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void mirror(struct Node* node){
if (node == NULL)
return;
else{
struct Node* temp;
//swapping the subtrees
mirror(node->left);
mirror(node->right);
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
//printing the inorder traversal
void print_tree(struct Node* node){
if (node == NULL)
return;
print_tree(node->left);
cout << node->data << " ";
print_tree(node->right);
}
int main(){
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
//printing the initial tree
cout << "Inorder traversal of the constructed" << endl;
print_tree(root);
mirror(root);
//printing the mirror tree
cout << "\nInorder traversal of the mirror tree" << endl;
print_tree(root);
return 0;
}输出结果
Inorder traversal of the constructed 4 2 5 1 3 Inorder traversal of the mirror tree 3 1 5 2 4
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短