#include <stdio.h>
#include <stdlib.h>
struct Treenode
{ int Data;
struct Treenode *Lchild, *Rchild;
};
void Setuptree(struct Treenode **T, int b, struct Treenode *p, int tag )
{ struct Treenode *x;
x=(struct Treenode *) malloc(sizeof(struct Treenode));
x->Data = b; x->Lchild = 0; x->Rchild = 0;
if ((*T)==0) (*T)=x;
else if (p != 0)
{ if (tag==0) { x->Lchild = p->Lchild; p->Lchild = x; }
else { x->Rchild = p->Rchild; p->Rchild = x; }
}
else if (tag==0)
{ p = (*T);
while (p->Lchild !=0) p=p->Lchild;
p->Lchild = x;
}
else { p = (*T);
while (p->Rchild !=0) p=p->Rchild;
p->Rchild = x;
}
}
void InOrder(struct Treenode *T){
if (T!= 0){
InOrder(T->Lchild);
printf("%4d",T->Data);
InOrder(T->Rchild);
}
}
int main(){
struct Treenode *T=0,*p, *(Q[20]);
int Front,Rear;
int A[100];
int i=0,j=0;
scanf("%d",&A[0]);
while(A[j++]!=-1){
scanf("%d",&A[j]);
}
Setuptree(&T, A[i++], p, 0); // 二叉树根结点
//printf("i = %d,j = %d\n",i,j);
int n = j-1;
/*for(int k=0;k<n;k++){
printf("%d ",A[k]);
}*/
while (i<n){
Front=0;
Rear=0;
Q[++Rear] = T;
while (Front<Rear){
p = Q[++Front];
if (p->Lchild!=0) Q[++Rear] = p->Lchild; // 左子树
else{
if (i<n) Setuptree(&T, A[i++], p, 0);
}
if (p->Rchild!=0) Q[++Rear] = p->Rchild; // 右子树
else{ if (i<n) Setuptree(&T, A[i++], p, 1);
}
}
}
InOrder(T);
return 0;
}
数据结构上级习题8:二叉排序树
最新推荐文章于 2023-12-07 22:23:44 发布