97. 二叉排序树

来源:互联网 发布:网络小贷公司英文翻译 编辑:程序博客网 时间:2024/06/04 18:34
#include<stdio.h>
#include<stdlib.h>
struct node{
int val;               // 结点值 
struct node* lchild;   // 左结点 
struct node* rchild;   // 右结点 
};
node *Creat()       // 创建结点 
{
node *T=(struct node*)malloc(sizeof(struct node));
T->lchild=T->rchild=NULL;
return T;
}
node *Insert(node *T,int x)   // 创建二叉排序树 
{
if(T==NULL){
T=Creat();
T->val=x;
return T;
}
else if(x<T->val) T->lchild=Insert(T->lchild,x);
else if(x>T->val) T->rchild=Insert(T->rchild,x);
return T;
}


int FindFather(node *FatherT,node *T,int x)  // 查找父结点 
{
if(x==T->val){
if(FatherT==NULL) return -1;
else return FatherT->val;
}
else if(x>T->val) return FindFather(T,T->rchild,x);
else if(x<T->val) return FindFather(T,T->lchild,x);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
node *T=NULL;
int k;
for(int i=0;i<n;i++){
scanf("%d",&k);
T=Insert(T,k);
int x=FindFather(NULL,T,k);
printf("%d\n",x);
}
}
return 0;
}
0 0
原创粉丝点击