upsk1   6년 전

#include <iostream>
using namespace std;
typedef struct Node {
char data;
Node* left;
Node* right;
}node;

void add(node* a, node* b) {
if (a->left == NULL) {//왼쪽 자식이 없으면 
a->left = b; 
}
else {
node* temp = a->left; //있으면 오른쪽 끝을 찾아가서
while (temp->right != NULL) {
temp = temp->right; //자식을 추가
}
temp->right = b;
}
}
void preorder(node* a) { //전위순회 
cout << a->data;//루트 출력
if (a->left != NULL)preorder(a->left); //왼쪽 

if (a->right != NULL)preorder(a->right); //오른쪽
}
void inorder(node* a) {
if (a->left != NULL)inorder(a->left); //왼쪽
 
cout << a->data; //루트출력

if (a->right != NULL)inorder(a->right);//오른쪽
}
void postorder(node* a){
if (a->left != NULL)postorder(a->left); //왼쪽

if (a->right != NULL)postorder(a->right);//오른쪽

cout << a->data;//루트출력
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
node a[127];
char temp1, temp2, temp3;
int n; cin >> n;
for (int i = 'A'; i < 'A' + n; i++) {
a[i].data = i;
a[i].left = NULL;
a[i].right = NULL;
}
for (int i = 0; i < n; i++) {
cin >> temp1 >> temp2 >> temp3;
if (temp2 != '.')add(&a[temp1], &a[temp2]);
if (temp3 != '.')add(&a[temp1], &a[temp3]);
}
for (int i = 'A'; i < 'A' + n; i++) {
cout << a[i].data << endl;
}
preorder(&a['A']);
cout << '\n';
inorder(&a['A']);
cout << '\n';
postorder(&a['A']);
}

재귀 구현 순서대로라면 inorder ,postorder 둘다 A가 마지막으로 출력되면 안되는데 

순서와는 다르게 값이 출력됩니다. 뭐가 잘못된건지 모르겠어서 질문드립니다


댓글을 작성하려면 로그인해야 합니다.