九度OJ 1201:二叉排序树 (二叉树)

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:4894

解决:2062

题目描述:

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

输入:

    输入第一行包括一个整数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 
提示:

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

来源:
2005年华中科技大学计算机保研机试真题

思路:

插入排序,前序中序后序遍历,建立二叉树的主要内容,不过缺了删除和查找。

主要每次循环开始时要重新初始化头结点。


代码:

#include 
#include 
 
#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


转载于:https://www.cnblogs.com/liangrx06/p/5083826.html

你可能感兴趣的:(九度OJ 1201:二叉排序树 (二叉树))