《算法笔记》9.4小节——数据结构专题(2)->二叉查找树(BST)->问题 A: 二叉排序树

问题 A: 二叉排序树

时间限制: 1 Sec  内存限制: 32 MB
提交: 519  解决: 225
[提交][状态][讨论版][命题人:外部导入]

题目描述

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

输入

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

输出

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

样例输入

1
2 
2
8 15 
4
21 10 5 39 

样例输出

2 
2 
2 
8 15 
8 15 
15 8 
21 10 5 39 
5 10 21 39 
5 10 39 21 

[提交][状态]

#include<iostream>
using namespace std;
struct node{
	int data;
	node *lchild;
	node *rchild;
};

node *newNode(int v){
	node *root=new node;
	root->data=v;
	root->lchild=root->rchild=NULL;
	return root;
}

void insert(node *&root,int x){
	if(root==NULL){
		root=newNode(x);
		return;
	}
	if(x==root->data){
		return;
	}else if(x<root->data){
		insert(root->lchild,x);
	}else{
		insert(root->rchild,x);
	}
}

node *create(int data[],int n){
	node *root=NULL;
	for(int i=0;i<n;i++){
		insert(root,data[i]);
	}
	return root;
}

void preOrder(node *root){
	if(root!=NULL){
		cout<<root->data<<" ";
		preOrder(root->lchild);
		preOrder(root->rchild);
	}
}
void inOrder(node *root){
	if(root!=NULL){
		inOrder(root->lchild);
		cout<<root->data<<" ";
		inOrder(root->rchild);
	}
}
void postOrder(node *root){
	if(root!=NULL){
		postOrder(root->lchild);
		postOrder(root->rchild);
		cout<<root->data<<" ";
	}
}

int main(){
	int n;
	while(cin>>n){
		int a[n];
		for(int i=0;i<n;i++){
			cin>>a[i];
		}
		node *NEW=create(a,n);
		preOrder(NEW);
		cout<<endl;

		inOrder(NEW);
		cout<<endl;

		postOrder(NEW);
		cout<<endl;
	}
	return 0;
}
发布了51 篇原创文章 · 获赞 7 · 访问量 7451

猜你喜欢

转载自blog.csdn.net/Jason6620/article/details/104077414