大致也就分两种,其中一种是静态建树,静态建树里面,可以是给每个点的子节点,也可以是给每个点的父节点,那种给先序/后续与中序来建树的就不说了,之说一下给出每个点父或子节点的情况。
1)只给出每个点的子节点:
8 1 -, - -, 0 -, 2 7, - -, - -, 5 -, 4 6
'-'表示无子节点;
struct node{
int l,r;
};
node arr[100];
bool isRoot[100]={0};
int change(char ch){//将‘-’转换为-1
if(ch=='-')return -1;
else{
isRoot[ch-'0']=1;
return ch-'0';
}
}
int find_root(){//寻找根节点
for(int i=0;i<n;i++)
if(!isRoot[i])
return i;
}
void creat(){//构建二叉树
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
char a,b;
scanf("%*c%c %c",&a,&b);//*表示只读取不赋值给变量,此处用来读取无用的回车
arr[i].l=change(a);
arr[i].r=change(b);
}
}
2)只给出每个点的子节点:
9 : 1 5 4 4 -1 4 5 3 6
这种情况看作是一个数组,每个位置存储着这个点的父节点,解决办法和上述大同小异。
struct node{
int num[100];
int index;
};
node arr[100];
void creat(){
int n;
int root;
scanf("%d",&n);
for(int i=0;i<n;i++){
int temp;
scanf("%d",&temp);
if(temp==-1)
root=i;
else {
arr[temp].num[index++]=i;
}
}
}
int maxdepth=0,num=0;
void dfs(int i,int depth){//顺带写了个深搜的求一下深度和最大深度的叶节点个数。
if(arr[i].index==0){
if(maxdepth<depth)
maxdepth=depth,
num=1;
if(maxdepth==depth)
num++;
return ;
}
for(int j=0;j<arr[i].index;j++)
dfs(arr[i].num[j],depth+1);
}