ALDS1_7_C Tree - Tree Work

Calendar Clock iconCalendar Clock icon

AOJ

# 目次

# 問題

# 解答

// C++ 14
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <math.h>

#define ll long long
#define Int int
#define loop(x, start, end) for(Int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)
#define rep(n) for(int x = 0; x < n; x++)
#define span(a,x,y) a.begin()+x,a.begin()+y
#define span_all(a) a.begin(),a.end()
#define len(x) (x.size())
#define last(x) (*(x.end()-1))

using namespace std;
#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;
}

リモートフリーランス。ウェブサービス、スマホアプリエンジニア。
東アジアを拠点に世界を移動しながら活動してます!

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

コメント