1.以孩子兄弟链表作为存储结构
//数据结构
typedef struct csnode{
elemtype data;
struct csnode *firstchild,*nextsibling;
}csnode,*cstree;
//算法
int depth(cstree t){
csnode *p;
int m,d;
if(t==null) return 0;
p=t->firstchild;
m=0; //最大深度初始为0
while(p){
d=depth(p);
if(d>m) m=d;//更新最大深度
p=p->nextsibling;
}
return m+1;//子树的最大深度加上根节点的深度
}
2.利用层次遍历,还是用上述数据结构
算法思想:利用队列,将节点按层次顺序入队,出队,访问。出队访问的时候,要判断该节点是否为该层最右节点(怎么判断??),如果是,深度加1。并且再出队访问下一层。
int depth( cstree *t){
if(t==null) return 0;
initqueue(Q);
int d=level=0;//d表示深度,level表示当前所在层
cstree last=p=t;//last表示该层最后一个节点
enqueue(Q,p);//根节点入队
while(!empty(Q)){
dequeue(Q,p);//出队
//先将p的孩子入队,以防遇到最右节点时,last找不到下一层的最右节点
if(p->firstchild){//如果存在孩子
p=p->firstchild;
enqueue(Q,p);
p=p->nextsibling;
while(p){//将所有的孩子入队
enqueue(Q,p->nextsibling);
p=p->nextsibling;
}//循环结束时p==null
}
if(p==last){
d++;
last=Q.data[Q.rear];
}
}
return d;
}