ALDS1_7_B Tree - Binary Trees

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 100001
#define NIL -1

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


int degree(int n, Node nodes[]) {
  if (nodes[n].left != NIL && nodes[n].right != NIL) return 2;
  if (nodes[n].left == NIL && nodes[n].right == NIL) return 0;
  return 1;
}

int sibling(int n, Node nodes[]) {
  if (nodes[n].parent == NIL) return NIL;
  int p = nodes[n].parent;
  if (nodes[p].left == n) return nodes[p].right;
  return nodes[p].left;
}

void depth(int n, int d, Node nodes[], int ds[]) {
    ds[n] = d;
    if (nodes[n].right != NIL) depth(nodes[n].right, d+1, nodes, ds);
    if (nodes[n].left != NIL) depth(nodes[n].left, d+1, nodes, ds);
}

int height(int n, Node nodes[], int hs[]) {
    int left = 0; int right = 0;
    if (nodes[n].left != NIL) left = 1 + height(nodes[n].left, nodes, hs);
    if (nodes[n].right != NIL) right = 1 + height(nodes[n].right, nodes, hs);
    hs[n] = (left > right) ? left : right;
    return hs[n];
}

void print(int i, Node nodes[], int ds[], int hs[]) {
    cout << "node " << i << ": ";
    cout << "parent = " << nodes[i].parent;
    cout << ", sibling = " << sibling(i, nodes);
    cout << ", degree = " << degree(i, nodes);
    cout << ", depth = " << ds[i];
    cout << ", height = " << hs[i];
    cout << ", ";

    if (nodes[i].parent == NIL) cout << "root";
    else if (nodes[i].left == NIL && nodes[i].right == NIL) cout << "leaf";
    else cout << "internal node";
    cout << endl;
}

int main() {
    int n, id, left, right, root, c;
    Node T[MAX];
    int D[MAX];
    int H[MAX];
    
    cin >> n;
    for (int i=0; i<n; i++) T[i].parent = NIL;
    
    for (int i=0; i<n; i++) {
        cin >> id >> left >> right;
        T[id].left = left;
        T[id].right = right;
        T[left].parent = id;
        T[right].parent = id;
    }
    
    for (int i=0; i<n; i++) {
        if (T[i].parent == NIL) {
            root = i;
            break;
        }
    }

    
    depth(root, 0, T, D);
    height(root, T, H);
    
    for (int i=0; i<n; i++) print(i, T, D, H);
    return 0;
}

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

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

コメント