AOJ

# # 解答

#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;
}


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

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