-
题目描述:
-
输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。
-
输入:
-
输入第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。
-
输出:
-
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。
每种遍历结果输出一行。每行最后一个数据之后有一个空格。
-
样例输入:
-
5 1 6 5 9 8
-
样例输出:
-
1 6 5 9 8 1 5 6 8 9 5 8 9 6 1
-
提示:
-
输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
思路:
插入排序,前序中序后序遍历,建立二叉树的主要内容,不过缺了删除和查找。
主要每次循环开始时要重新初始化头结点。
代码:
#include <stdio.h>
#include <stdlib.h>
#define N 100
struct node {
int k;
struct node *l;
struct node *r;
};
struct node *create (struct node *h, int k)
{
if (h == NULL)
{
struct node *p = malloc(sizeof(struct node));
p->k = k;
p->l = NULL;
p->r = NULL;
return p;
}
if (k == h->k)
return h;
if (k < h->k)
h->l = create(h->l, k);
else
h->r = create(h->r, k);
return h;
}
void preOrder(struct node *h)
{
if (h == NULL)
return;
printf("%d ", h->k);
preOrder(h->l);
preOrder(h->r);
}
void infOrder(struct node *h)
{
if (h == NULL)
return;
infOrder(h->l);
printf("%d ", h->k);
infOrder(h->r);
}
void postOrder(struct node *h)
{
if (h == NULL)
return;
postOrder(h->l);
postOrder(h->r);
printf("%d ", h->k);
}
void delete(struct node *h)
{
if (h == NULL)
return;
delete(h->l);
delete(h->r);
free(h);
}
int main()
{
int i, n, tmp;
struct node *h = NULL;
while(scanf("%d", &n) != EOF)
{
h = NULL;
for (i=0; i<n; i++)
{
scanf("%d", &tmp);
//printf("i=%d\n", i);
h = create(h, tmp);
}
preOrder(h);
printf("\n");
infOrder(h);
printf("\n");
postOrder(h);
printf("\n");
delete(h);
}
return 0;
}
/**************************************************************
Problem: 1201
User: liangrx06
Language: C
Result: Accepted
Time:60 ms
Memory:912 kb
****************************************************************/