aoj

ALDS1_7_C Tree - Tree Work

ALDS1_7_C Tree - Tree Work
Feb. 2, 2020, 1:52 p.m.

目次

問題

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#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;
}