文章

81

粉丝

0

获赞

275

访问

10.5k

头像
二叉排序树2 题解:
P1411 华中科技大学机试题
发布于2025年3月25日 16:20
阅读数 33

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
	int c;
	struct node *r,*l;  
} *Tree;
void CreateTree(Tree &T,int x){
	if(T==NULL){
	    T=new node;
		T->c=x;
		T->r=NULL;
		T->l=NULL;
		return;
	}
	if(T->c==x) return ;
	else if(x<T->c){
		CreateTree(T->l,x);
	}else{
		CreateTree(T->r,x);
	}
}
void visitPre(Tree T){
	if(T){
		cout<<T->c<<" ";
		visitPre(T->l);
		visitPre(T->r);
	}
}
void visitZ(Tree T){
	if(T){
		visitZ(T->l);
		cout<<T->c<<" ";
		visitZ(T->r);
	}
}
void visitB(Tree T){
	if(T){
		visitB(T->l);
		visitB(T->r);
		cout<<T->c<<" ";
	}
}
int main(){
	int n;
	while(cin>>n){
	Tree T=NULL;
	int x;
	for(int i=0;i<n;i++){
	    cin>>x;
	    CreateTree(T,x);
	    
	}
	visitPre(T);
	cout<<endl;
	visitZ(T);
	cout<<endl;
	visitB(T);
	cout<<endl;
	}
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发