struct二叉树,全re求救
查看原帖
struct二叉树,全re求救
1118703
xiuman楼主2024/3/4 19:24
#include<bits/stdc++.h>
using namespace std;
#define maxn 2147483647
int cnt=0;
struct node{
	int data;
	int rent;
	node *leftchild;
	node *rightchild;
}*root;
node* buynode(int x){
	node* newnode=(node*)malloc(sizeof(node));
	if(newnode==NULL){
		cout<<"false";
		exit(-1);
	}
	newnode->data=x;
	newnode->rent=1;
	newnode->leftchild=NULL;
	newnode->rightchild=NULL;
}
void rentright(node *root){
	root->rent++;
	if(root->leftchild!=NULL)rentright(root->leftchild);
	if(root->rightchild!=NULL)rentright(root->rightchild);
}
int rentleft(node* root){
	node* cur=root;
	int a=root->rent;
	while(cur->leftchild!=NULL){
		cur=cur->leftchild;
	}
	return a-cur->rent+1;
}
void insertnode(int x,node** root){
	node* newnode=buynode(x);
	if(*root==NULL){
		*root=newnode;
	}
	else{
		node* cur=*root;
		while(cur!=NULL){
			if(x>cur->data){
				newnode->rent+=rentleft(cur);
				if(cur->rightchild==NULL){
					cur->rightchild=newnode;
					return;
				}
				cur=cur->rightchild;
			}
			else if(x<cur->data){
				cur->rent++;
				if(cur->rightchild!=NULL)rentright(cur->rightchild);
				if(cur->leftchild==NULL){
					cur->leftchild=newnode;
					return;
				}
				cur=cur->leftchild;
			}	
		}
	}
}
int checkx(int x,node* root){//2
	node* cur=root;
	while(1){
		if(x==cur->rent)return cur->data;
		if(x>cur->rent)cur=cur->rightchild;
		else if(x<cur->rent)cur=cur->leftchild;
	}
}
int checkrent(int x,node *root){//1
	node* cur=root;
//	if(x<checkx(1,root))return 1;
	while(1){
		if(cur->data==x)return cur->rent;
		if(x>cur->data){
			if(cur->rightchild==NULL){
				return cur->rent+1;
			}
			cur=cur->rightchild;
		}
		if(x<cur->data){
			if(cur->leftchild==NULL){
				return cur->rent;
			}
			cur=cur->leftchild;
		}	
	}
}
int checkfront(int x,node* root){//3
	node* cur=root;
	int rentx=checkrent(x,root);
	if(rentx==1)return -maxn;
	return checkx(rentx-1,root);
}
int checkback(int x,node* root){
	node* cur=root;
	int rentx=checkrent(x,root);
	if(rentx==cnt+1)return maxn;
	if(x==checkx(rentx,root))return checkx(rentx+1,root);
	else return checkx(rentx,root);
}
void print(node* root){
	cout<<root->data<<" "<<root->rent<<" "<<endl;
	if(root->leftchild!=NULL)print(root->leftchild);
	if(root->rightchild!=NULL)print(root->rightchild);
}
int main(){
	int q;
	cin>>q;
	int s,a;
	root=NULL;
	for(int i=1;i<=q;i++){
		cin>>s>>a;
		if(s==1)cout<<checkrent(a,root)<<endl;//查询a的排名 
		if(s==2)cout<<checkx(a,root)<<endl;//查询排名为a的数 
		if(s==3)cout<<checkfront(a,root)<<endl;//求比a小的第一个数 
		if(s==4)cout<<checkback(a,root)<<endl;//求比a大的第一个数 
		if(s==5){//插入 
			insertnode(a,&root);
			cnt++;	
		}
	}
//	cout<<cnt;
//	print(root);
	//cout<<root->rent;
}
2024/3/4 19:24
加载中...