华中科技大学-二叉排序树

在这里插入图片描述
在这里插入图片描述
我做本题时的一个错误就是,没有声明node *t=NULL,直接生命node *t,以为这样能默认t=NULL,结果发现并不是这样的。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
struct node{
	node *lchild,*rchild;
	int data;
}; 
node tree[maxn];
int loc;
node *creat(){
	tree[loc].lchild=tree[loc].rchild = NULL;
	return &tree[loc++];
}
node *insert(node *t,int a){
	if(t==NULL){
		t = creat();
		t->data = a;
		return t;
	}
	else if(t->data>a){
		t->lchild = insert(t->lchild,a);
	}
	else if(t->data<a){
		t->rchild = insert(t->rchild,a);
	}
	return t;
}
void preOrder(node *t){
	printf("%d ",t->data);
	if(t->lchild!=NULL){
		preOrder(t->lchild);
	}
	if(t->rchild!=NULL){
		preOrder(t->rchild);
	}
}
void inOrder(node *t){
	if(t->lchild!=NULL) inOrder(t->lchild);
	printf("%d ",t->data);
	if(t->rchild!=NULL) inOrder(t->rchild);
}
void postOrder(node *t){
	if(t->lchild!=NULL) postOrder(t->lchild);
	if(t->rchild!=NULL) postOrder(t->rchild);
	printf("%d ",t->data);
}
int main(){
	int n,x;
	while(scanf("%d",&n)!=EOF){
		node *t = NULL;//必须声明t是NULL的 
		loc = 0;
		for(int i=0;i<n;i++){
		 scanf("%d",&x);
		 t = insert(t,x);
	}
	preOrder(t);
	printf("\n");
	inOrder(t);
	printf("\n");
    postOrder(t);
	printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_37762592/article/details/88761020
今日推荐