有根树的表达
2019-08-02
11:17:53
题目链接
https://vjudge.net/problem/Aizu-ALDS1_7_A
#include<bits/stdc++.h> using namespace std; #define MAX 100005 #define NIL -1 struct Node{ int p; //节点U的父节点 int l; //最左侧的子节点 int r; //右侧紧邻的兄弟节点 }T[MAX]; int n; int D[MAX]; void print(int u) { cout << "node " << u <<": "; cout << "parent = " << T[u].p <<", "; cout << "depth = " << D[u] << ", "; if(T[u].p == NIL) cout << "root, "; else if(T[u].l == NIL) cout << "leaf, "; else cout << "internal node, "; cout << "["; for(int i = 0, c = T[u].l; c != NIL; i++, c = T[c].r) { if(i) cout << ", "; cout << c; } cout << "]" << endl; } int rec(int u,int p) // 根节点,p是深度 { D[u] = p; //这个是为了记录每一个节点的深度 if(T[u].r != NIL) rec(T[u].r,p); if(T[u].l != NIL) rec(T[u].l, p+1); } int main() { cin >> n; int id, k, c, l, r; for(int i = 0; i < n; i++) //初始化 { T[i].p = T[i].l = T[i].r = NIL; } for(int i = 0; i < n; i++) { cin >> id >> k ; //id节点的编号,k节点的度数 for(int j = 0; j < k; j++) { cin >> c; if(j == 0) { T[id].l = c; // 编号为id的最左侧子节点 } else { T[l].r = c; } l = c; T[c].p = id; //存每个节点的父节点 } } for(int i = 0; i < n; i++) { if(T[i].p == NIL) r = i; } rec(r, 0); for(int i = 0; i < n; i++) { print(i); //print是一个函数 } return 0; }