题目描述
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述:
输入第一行包括一个整数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>
#include <cstdlib>
using namespace std;
typedef struct Node {
int data;
struct Node * pLeftChild;
struct Node * pRightChild;
} Node,* PNode;
void insert(PNode& pT,int k) {
if (pT == NULL) {
pT = (PNode)malloc(sizeof(Node));
pT->data = k;
pT->pLeftChild = pT->pRightChild = NULL;
return ;
}
int value = pT->data;
if (k == value) {
return ;
} else if (k < value) {
insert(pT->pLeftChild,k);
} else {
insert(pT->pRightChild,k);
}
}
void preorder(PNode pT) {
if (pT == NULL) {
return;
}
cout << pT->data << " ";
preorder(pT->pLeftChild);
preorder(pT->pRightChild);
}
void inorder(PNode pT) {
if (pT == NULL) {
return;
}
inorder(pT->pLeftChild);
cout << pT->data << " ";
inorder(pT->pRightChild);
}
void postorder(PNode pT) {
if (pT == NULL) {
return;
}
postorder(pT->pLeftChild);
postorder(pT->pRightChild);
cout << pT->data << " ";
}
int main() {
int n;
int t;
PNode pT = NULL;
while(cin >> n) {
PNode pT = NULL;
for (int i = 1; i <= n; i ++) {
cin >> t;
insert(pT,t);
}
preorder(pT);
cout << endl;
inorder(pT);
cout << endl;
postorder(pT);
cout << endl;
}
}