九度OJ 1201 二叉排序树

题目地址:http://ac.jobdu.com/problem.php?pid=1201

题目描述:

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

输入:

    输入第一行包括一个整数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>
 
typedef struct btree{
    int data;
    struct btree * left;
    struct btree * right;
}BTree;
 
BTree * search (BTree * root, int data){
    BTree * p = root;
    BTree * pre = NULL;
 
    while (p != NULL){
        pre = p;
        if (p->data > data)
            p = p->left;
        else if (p->data < data)
            p = p->right;
        else
            return NULL;
    }
    return pre;
}
 
void insert (BTree ** root, int data){
    BTree * p = NULL;
    BTree * s = *root;
    BTree * pre = NULL;
 
    p = (BTree *)malloc(sizeof(BTree));
    p->data = data;
    p->left = p->right = NULL;
    if ((*root) == NULL){
        *root = p;
        return;
    }
    pre = search (*root, data);
    if (pre != NULL){
        if (pre->data > data)
            pre->left = p;
        if (pre->data < data)
            pre->right = p;
    }
 
}
 
BTree * build_btree (int tree[], int n){
    int i;
    BTree * root = NULL;
 
    for (i=1; i<=n; ++i){
        insert (&root, tree[i]);
    }
    return root;
}
 
void preorder (BTree * root){
    BTree * p = root;
    if (p != NULL){
        printf ("%d ", p->data);
        preorder (p->left);
        preorder (p->right);
    }
}
 
void inorder (BTree * root){
    BTree * p = root;
    if (p != NULL){
        inorder (p->left);
        printf ("%d ", p->data);
        inorder (p->right);
    }
}
 
void postorder (BTree * root){
    BTree * p = root;
    if (p != NULL){
        postorder (p->left);
        postorder (p->right);
        printf ("%d ", p->data);
    }
}
 
void deletetree (BTree * root){
    BTree * p = root;
    if (p != NULL){
        deletetree (p->left);
        deletetree (p->right);
        free (p);
    }
}
 
int main(void){
    int n, i;
    int tree[101];
    BTree * root = NULL;
 
    while (scanf ("%d", &n) != EOF){
        for (i=1; i<=n; ++i)
            scanf ("%d", &tree[i]);
        root = build_btree (tree, n);
        preorder (root);
        putchar ('\n');
        inorder (root);
        putchar ('\n');
        postorder (root);
        putchar ('\n');
        deletetree(root);
    }
     
    return 0;
}

参考资料: http://zh.wikipedia.org/wiki/%E4%BA%8C%E5%85%83%E6%90%9C%E5%B0%8B%E6%A8%B9

你可能感兴趣的:(二叉树,二叉树遍历,九度OJ,考研机试)