给定关键字序列为{16,5,17,29,11,3,15,20} ,按表中元素的顺序依次插入,建立相应的二叉排序树,给出其中序序列。


给定关键字序列为{16,5,17,29,11,3,15,20} ,按表中元素的顺序依次插入,建立相应的二叉排序树,给出其中序序列。


参考施老师等编著的《数据结构》,注意要理解代码,不要只是为了抄作业。

 #include<iostream>//计算机系蓝多多算法实验七
using namespace std;
typedef int KeyType;
typedef struct {
    KeyType  key;
} ElemType;
typedef struct BitNode {
    ElemType data;
    struct BitNode* lchild, * rchild;
}BitNode, * BiTree;

BiTree insert(BiTree b, BiTree s)
{
    if (b == NULL) b = s;
    else if (s->data.key > b->data.key) b->rchild = insert(b->rchild, s);
    else if (s->data.key < b->data.key) b->lchild = insert(b->lchild, s);
    return b;
}

BiTree creat() {
    int k;
    BiTree t, s;
    t = NULL;
    scanf_s("%d", &k);
    while (k != -1) {
        s = (BiTree)malloc(sizeof(BitNode));
        s->data.key = k;
        s->lchild = NULL;
        s->rchild = NULL;
        t = insert(t, s);
        scanf_s("%d", &k);
    }
    return t;
}
void inorder(BiTree t) {
    if (t) {
        inorder(t->lchild);
        printf_s("%3d", t->data);
        inorder(t->rchild);
    }
}
void main() {
    BiTree t;
    printf_s("input data,end in -1:");
    t = creat();
    printf_s("The inorder sequence is:");
    inorder(t);
}

运行结果:略

猜你喜欢

转载自blog.csdn.net/qq_43554335/article/details/106842999
今日推荐