Trong hướng dẫn này, chúng ta sẽ phản ánh cây nhị phân đã cho.
Hãy xem các bước để giải quyết vấn đề.
-
Viết một nút cấu trúc.
-
Tạo cây nhị phân với dữ liệu giả.
-
Viết một hàm đệ quy để tìm bản sao của cây nhị phân đã cho.
-
Gọi hàm một cách đệ quy với các nút trái và phải.
-
Hoán đổi dữ liệu nút bên trái với dữ liệu nút bên phải.
-
-
In cây.
Ví dụ
Hãy xem mã.
#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;
} Đầu ra
Nếu bạn chạy đoạn mã trên, thì bạn sẽ nhận được kết quả sau.
Tree: 4 2 5 1 3 Mirror of the Tree: 3 1 5 2 4
Kết luận
Nếu bạn có bất kỳ câu hỏi nào trong hướng dẫn, hãy đề cập đến chúng trong phần bình luận.