二叉排序树建立及前中后序遍历

题目描述

输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。

输入描述:

输入第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。

输出描述:

可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。
每种遍历结果输出一行。每行最后一个数据之后有一个空格。

输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

示例1

输入

复制

5
1 6 5 9 8

输出

复制

1 6 5 9 8 
1 5 6 8 9 
5 8 9 6 1 

二叉排序树(二叉搜索树)的递归方法建立,以及前中后序遍历。

#include <iostream>
using namespace std;
struct NODE{
	int data;
	NODE *l;
	NODE *r;
};
bool creat(NODE * &root,int a){
	if(root==NULL){
		root=new NODE;
	    root->data=a;
	    root->l=NULL;
	    root->r=NULL;
	    return true;
	}
	if(a>root->data){
		return creat(root->r,a);
	}
	else{
		return creat(root->l,a);
	}
}
void preorder(NODE *root){
	cout<<root->data<<" ";
	if(root->l!=NULL){
		preorder(root->l);
	}
    if(root->r!=NULL){
    	preorder(root->r); 
	}
}
void midorder(NODE *root){
    if(root->l!=NULL){
		midorder(root->l);
	}
	cout<<root->data<<" ";
	if(root->r!=NULL){
		midorder(root->r);
	}
}
void postorder(NODE *root){
	if(root->l!=NULL){
		postorder(root->l);
	}
	if(root->r!=NULL){
		postorder(root->r);
	}
	cout<<root->data<<" ";
}
int main(){
	int n;
	while(cin>>n){
		int num[102];
		NODE *root=NULL;
		for(int i=0;i<n;i++){
			cin>>num[i];
		}
		bool temp[102];
		for(int i=0;i<n;i++){
			temp[i]=false;
		}
		for(int i=0;i<n;i++){
			for(int j=i+1;j<n;j++){
				if(num[j]==num[i]){
					temp[j]=true;
				}
			}
		}
		int k=0;
		int num1[102];
		for(int i=0;i<n;i++){
			if(!temp[i]){
				num1[k]=num[i];
				k++;
			}
		}
		NODE *roo=new NODE;
		roo->data=num1[0];
		roo->l=NULL;
		roo->r=NULL;
		for(int i=1;i<k;i++){
			creat(roo,num1[i]);
		}
		preorder(roo);
		cout<<endl;
		midorder(roo);
		cout<<endl;
		postorder(roo);
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_chen_l/article/details/81170174