題目:已知有n個結點的樹以雙親表示法存儲在一維數組中。請設計一個算法求樹中每個結點的層次和樹的高度,將求得的每個結點的層次保存在一維數組C中,並分析你所設計的算法的時間複雜度。
int Depth(PTree t){
//編寫求雙親表示法表示的樹的深度的算法
int maxdepth=0 , i, temp, f; //設初始深度爲0
for(i=0;i<t.n;i++){ //t.n表示樹t的第n個結點
temp=0;
f=i;
while(f > -1 ){
temp++;
f=t.nodes[f].parent;
}
if(temp>maxdepth) maxdepth=temp;
}
return maxdepth;
}