在 C++ 程序中创建给定二叉树的镜像树
在本教程中,我们准备反映给出的二叉树。
我们来看看解决该问题的步骤。
编写一个 struct 节点。
使用虚拟数据创建二叉树。
编写一个递归函数,以查找给定二叉树的镜像。
使用左右节点以递归方式调用函数。
交换左节点数据和右节点数据。
打印树。
示例
我们来看看代码。
#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 = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void convertTreeToItsMirror(struct Node* node) {
if (node == NULL) {
return;
}
else {
struct Node* temp;
convertTreeToItsMirror(node->left);
convertTreeToItsMirror(node->right);
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
void printTree(struct Node* node) {
if (node == NULL) {
return;
}
printTree(node->left);
cout << node->data << " ";
printTree(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 << "Tree: ";
printTree(root);
cout << endl;
convertTreeToItsMirror(root);
cout << "Mirror of the Tree: ";
printTree(root);
cout << endl;
return 0;
}输出
如果你运行上述代码,你将得到以下结果。
Tree: 4 2 5 1 3 Mirror of the Tree: 3 1 5 2 4
结论
如果你有任何关于本教程的问题,请在评论部分提及。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP