在 C++ 中将二叉树转换为其镜像树
c++server side programmingprogramming更新于 2024/10/3 0:43:00
在本教程中,我们将讨论将二叉树转换为其镜像树的程序。
为此,我们将提供一棵二叉树。我们的任务是交换左侧和右侧的值,从给定的二叉树创建镜像树。
示例
#include<bits/stdc++.h> using namespace std; //二叉树节点结构 struct Node{ int data; struct Node* left; struct Node* right; }; //创建没有子节点的新节点 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; //交换子树 mirror(node->left); mirror(node->right); temp = node->left; node->left = node->right; node->right = temp; } } //打印中序遍历 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); //打印初始树 cout << "中序遍历构造的<<< endl; print_tree(root); mirror(root); //打印镜像树 cout << "\n镜像树的中序遍历<< endl; print_tree(root); return 0; }
输出
构造的中序遍历 4 2 5 1 3 镜像树的中序遍历 3 1 5 2 4