```c
```c
#include<stdio.h>#include<stdlib.h>#include<iostream>
using namespace std;constint nmax=100;int f[nmax+1];int s[nmax+1][nmax+1];int tot;char a[nmax];intGetDepth(int x){if(!s[x][0])//如果x号父亲没有儿子了 return1;//please finish the following parts,深度为1 int ans=1;for(int i=1;i<=s[x][0];i++)//please finish the following parts,s[x][0]存的是x号父亲的儿子个数
ans=max(ans,GetDepth(s[x][i])+1);//深度为原来的ans和所有子树的深度+1(父亲)中间的最大值 return ans;}voidPrint(int tot,int idx,char c)//tot是getdepth的返回值 ans{for(int i=1;i<idx;i++)
cout<<'#';
cout<<c;for(int i=0;i<tot-idx;i++)
cout<<'#';
cout<<endl;}voidDFS(int x,int d){Print(tot,d,a[x]);//d对应的是index,a[x]对应的是char,d是怎么得到的呢?一开始输入的是1 if(!s[x][0])return;//please finish the following partsfor(int i=1;i<=s[x][0];i++)//调用一次DFS打印一次 i遍历的范围是s[1][0](即1号父亲的子树个数) DFS(s[x][i],d+1);//please finish the following parts 后面的子树也会作为父亲,递归遍历 //Print(tot,d+1,a[s[x][i]]) 递归一次index+1,说明往下一层了,所以输出的字母要往后一格 return;}intmain(){int n;
cin>>n;for(int i=1;i<=n;i++){//注意循环是从1开始的
cin>>a[i]>>f[i];//a和f存的是什么?a存的是字母,f存的是父亲的编号 int p=f[i];//p是第i个元素父亲的编号
s[p][0]++;//s存的是什么?//s[p][0]记录的是p父亲儿子的个数吗?
s[p][s[p][0]]=i;//p父亲的第s[p][0]个儿子输入的编号是i }
tot=GetDepth(1);DFS(1,1);return0;}
#include<iostream>usingnamespace std;structNode{char data;int parent;//r和lchild的意义是什么?记录在node在数组中的位置 int lchild, rchild;//左儿子右兄弟 } nodes[101];//用数组存,不是链表! int n, lastchild[101];//lastchild是干嘛用的? voidbuildTree(){
cin >> n;for(int i =1; i <= n; i++)
cin >> nodes[i].data >> nodes[i].parent;for(int i =2; i <= n; i++){int f = nodes[i].parent;//f是新创建结点的父亲编号 if(lastchild[f]==0)//lastchild[f]=0意味着没有兄弟了,要往下创建儿子了
nodes[f].lchild = lastchild[f]= i;//lastchild[f]的值记录着正在创建的最后一个子节点 else{int j = lastchild[f];//please finish the following parts
nodes[j].rchild = lastchild[f]= i;//lastchild[f]不等于0,创建兄弟,即右儿子 }//i每加一次就要创建一个左儿子或右儿子,意思是第i个元素是上一个元素(若是兄弟,则是i-1,若是父亲则f(f=nodes[i].parent))的左子树或者右子树 }}voidPreorder(Node &root){//please finish the following parts
cout << root.data;//注意判断条件 if(root.lchild !=0)Preorder(nodes[root.lchild]);if(root.rchild !=0)Preorder(nodes[root.rchild]);}voidMidorder(Node &root){//please finish the following partsif(root.lchild !=0)Midorder(nodes[root.lchild]);
cout << root.data;if(root.rchild !=0)Midorder(nodes[root.rchild]);}voidPostorder(Node &root){//please finish the following partsif(root.lchild !=0)Postorder(nodes[root.lchild]);if(root.rchild !=0)Postorder(nodes[root.rchild]);
cout << root.data;}intmain(){buildTree();Preorder(nodes[1]); cout<<"\n";Midorder(nodes[1]); cout<<"\n";Postorder(nodes[1]);return0;}