二叉树的层次建立方式(C语言)

二叉树的层次建立方式(C语言)

二叉树的层次建立方式与先序、中序、后序建树的方式有较大区别。类似于深搜用递归、广搜用队列。

输入一组整数,0代表结点不存在,-1代表输入结束
有很多C++版本了,所以在这里完全用C语言实现

#include 
#include 
typedef struct node{
    int data;
    struct node *lchild, *rchild;
}BinTree;
BinTree *que[1000];
int s[1000],ss = 0;
int front = 0, rear = 0;
int num;
BinTree* CreateBiTree(void)
{
    int n = num;
    int d,d1,d2;
    BinTree *t, *bt, *q;
    d = s[ss++];
    if(d != 0 && d != -1){
        bt = (BinTree*)malloc(sizeof(BinTree));
        bt->data = d;
        bt->rchild = bt->lchild = NULL;
        que[rear++] = bt;
        n--;
    }
    else
        return NULL;
    while(n){
        t = que[front];
        front++;
        if(n == 0)
            break;
        d1 = s[ss++];
        if(d1 == -1)
            break;
        if(d1 != 0){
            q = (BinTree*)malloc(sizeof(BinTree));
            q->data = d1;
            t->lchild = q;
            q->rchild = q->lchild = NULL;
            que[rear++] = q;
            n--;
        }
        else
            t->lchild = NULL;
        d2 = s[ss++];
        if(d2 == -1)
            break;
        if(d2 != 0){
            q = (BinTree*)malloc(sizeof(BinTree));
            q->data = d2;
            t->rchild = q;
            q->rchild = q->lchild = NULL;
            que[rear++] = q;
            n--;
        }
        else
            t->rchild = NULL;
    }
    return bt;
}
void PrintBTree(BinTree *bt)
{
    if(bt != NULL){
        printf("%d ", bt->data);
        PrintBTree(bt->lchild);
        PrintBTree(bt->rchild);
    }
}
int main(void)
{
    BinTree *root;
    int n, i, j, k;
    num = 0, ss = 0;
    front = rear = 0;
    while(1){
        scanf("%d", &s[num]);
        if(s[num] == -1)
            break;
        num++;
    }
    root = CreateBiTree();
    PrintBTree(root);
    printf("\n");
    return 0;
}

你可能感兴趣的:(数据结构与算法)