来源:牛客网
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述:
输入第一行包括一个整数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
解题思路:
二叉排序树的构建与三种遍历方式。
AC代码:
#include<iostream>
#include<stdio.h>
using namespace std;
struct node {
node *left;
node *right;
int num;
}tree[105];//静态数组
int cnt;//静态数组中被使用元素的个数
node *creat() {//申请新结点
tree[cnt].left = tree[cnt].right = NULL;
return &tree[cnt++];
}
node *build(int x, node *t) {
if (t == NULL) {//若当前树为空
t = creat();//建立新结点
t->num = x;
}
else if (x < t->num) {//进入左子树
t->left = build(x, t->left);
}
else if (x > t->num) {//进入右子树 若根结点数值与x相等,按照题目要求直接忽略
t->right = build(x, t->right);
}
return t;//返回根结点指针
}
void pre_order(node *root) {//前序遍历
if (root == NULL) return;
printf("%d ", root->num);
pre_order(root->left);
pre_order(root->right);
}
void in_order(node *root) {//中序遍历
if (root == NULL) return;
in_order(root->left);
printf("%d ", root->num);
in_order(root->right);
}
void post_order(node *root) {//后序遍历
if (root == NULL) return;
post_order(root->left);
post_order(root->right);
printf("%d ", root->num);
}
int main() {
int n, x;
while (scanf("%d", &n)!=EOF) {
cnt = 0;
node *t = NULL;
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
t = build(x, t);
}
pre_order(t);
printf("\n");
in_order(t);
printf("\n");
post_order(t);
printf("\n");
}
return 0;
}