AOJ

# # 解答

#define MAX 25
#define NIL -1

struct Node {
int parent;
int left;
int right;
};

Node nodes[MAX];

void inorder(int node) {
if (nodes[node].left != NIL) inorder(nodes[node].left);
cout << node << " ";
if (nodes[node].right != NIL) inorder(nodes[node].right);
}

void preorder(int node) {
cout << node << " ";
if (nodes[node].left != NIL) preorder(nodes[node].left);
if (nodes[node].right != NIL) preorder(nodes[node].right);
}

void postorder(int node) {
if (nodes[node].left != NIL) postorder(nodes[node].left);
if (nodes[node].right != NIL) postorder(nodes[node].right);
cout << node << " ";
}

int main(void) {
int n, x, left, right, root;
cin >> n;
for (int i=0; i<n; i++) nodes[i].parent = NIL;

for (int i=0; i<n; i++) {
cin >> x >> left >> right;
nodes[left].parent = x;
nodes[right].parent = x;
nodes[x].left = left;
nodes[x].right = right;
}

for (int i=0; i<n; i++) {
if (nodes[i].parent == NIL) {
root = i;
break;
}
}

cout << "Preorder" << endl;
preorder(root); cout << endl;
cout << "Inorder" << endl;
inorder(root); cout << endl;
cout << "Postorder" << endl;
postorder(root); cout << endl;
}


リモートフリーランス。ウェブサービス、スマホアプリエンジニア。

お仕事のご依頼・お問い合わせはこちら