有根树的表达,题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_A
思路:
建立一个 左子右兄弟树 ; 每个节点中含有的属性是:
struct node{
int num;
int parent,left,right;//left is child, right is sibling
};
初始化中把所有属性全部赋为NIL(-1),每个节点的parent存自己父亲节点的坐标,left存自己最左侧的孩子节点的坐标,right存最靠近自己右侧的兄弟的坐标。
对于父亲节点而言,只能保留最左侧孩子节点的坐标,对于每一个孩子节点而言,只保留最靠近自己的兄弟节点的坐标。
求节点深度的方法有2种:
1.我的方法是向上遍历到没有父亲节点为止,遍历的长度就是深度
2.建立对应于每个节点的深度数组,每个节点的值对应于树种相应节点的深度。实现过程如下:
int Depth[maxx];
// 递归得求深度
void rec(int u, int depth) {
Depth[u] = depth;
if (tree[u].r != NIL) // 右侧兄弟设置为相同深度
rec(tree[u].r, depth);
if (tree[u].l != NIL) // 最左侧子结点的深度设置为自己的深度 + 1
rec(tree[u].l, depth + 1);
}
我实现的代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxx 100010
#define NIL -1
struct node{
int num;
int parent,left,right;//left is child, right is sibling
};
node tree[maxx];
int get_depth(int x){
int depth=0;
while(tree[x].parent!=NIL){
x=tree[x].parent;
depth++;
}
return depth;
}
int main (){
for(int i=0;i<maxx;i++) {
tree[i].parent=NIL;
tree[i].left=NIL;
tree[i].right=NIL;
}
int n;
cin>>n;
int a,b,c,d;
for(int i =0;i<n;i++){
cin>>a>>b;
tree[i].num=a;
for(int j=0;j<b;j++){
if(j==0) {
cin>>c;
tree[tree[i].num].left=c;
tree[c].parent=tree[i].num;
}
else{
cin>>d;
tree[c].right=d;
tree[d].parent=tree[i].num;
c=d;
}
}
}
for(int i=0;i<n;i++){
printf("node %d: parent = %d, depth = %d, ",i,tree[i].parent,get_depth(i));
if(tree[i].parent==NIL) printf("root, [");
else if(tree[i].left==NIL) printf("leaf, [");
else printf("internal node, [");
if(tree[i].left!=NIL) {
printf("%d",tree[i].left);
int xx=tree[i].left;
while(tree[xx].right!=NIL){
printf(", %d",tree[xx].right);
xx=tree[xx].right;
}
}
printf("]\n");
}
return 0;
}
错点:
1.读入时所用的i仅仅是为了计n个数,对于节点的序号没有意义,节点的编号由输入的编号num决定。
2.判断是否输出root时,应该判断该节点是否有父亲节点,而不能直接判断num是不是0;因为num=0不一定是根节点