이 튜토리얼에서는 주어진 바이너리 트리를 반영할 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
구조체 노드를 작성하십시오.
-
더미 데이터로 바이너리 트리를 생성합니다.
-
주어진 이진 트리의 미러를 찾는 재귀 함수를 작성하십시오.
-
왼쪽 및 오른쪽 노드를 사용하여 함수를 재귀적으로 호출합니다.
-
왼쪽 노드 데이터를 오른쪽 노드 데이터로 교환합니다.
-
-
트리를 인쇄합니다.
예시
코드를 봅시다.
#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
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.