北邮OJ 二叉排序树
#include <bits/stdc++.h>
using namespace std;
typedef struct node{
int data;
struct node* lchild;
struct node* rchild;
}Node;
Node* insert(Node* node,int x){
if(node==NULL){
node=(Node*)malloc(sizeof(Node));
node->data=x;
node->lchild=NULL;
node->rchild=NULL;
return node;
}
else if(x<node->data)
node->lchild=insert(node->lchild,x);
else if(x>=node->data)
node->rchild=insert(node->rchild,x);
return node;
}
void in(Node* node){
if(node){
in(node->lchild);
printf("%d",node->data);
in(node->rchild);
}
}
int find(Node* father,Node* node,int x){
if(node->data==x){
if(father==NULL)
return -1;
else
return father->data;
}
else if(node->data>x)
find(node,node->lchild,x);
else
find(node,node->rchild,x);
}
int main(){
int n,temp;
Node *node=NULL;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&temp);
node=insert(node,temp);
int x;
x=find(NULL,node,temp);
printf("%d\n",x);
}
//in(node); //debug
}