北邮OJ 130 二叉排序树

北邮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 
	
}

猜你喜欢

转载自blog.csdn.net/bingkuoluo_/article/details/88808743
今日推荐