二叉排序树的实现与输出

输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。
前序遍历:根->左->右
中序遍历:左->根->右
后序遍历:左->右->根

struct Tree
{
    int data;
    Tree* Left;
    Tree* Right;
};

bool Insert(int data,Tree *&T)
{
    if (T == NULL)
    {
        T = new Tree;
        T->data = data;
        T->Left = T->Right = NULL;
    }
    if (T->data == data)
        return false;
    else {
        if (data < T->data)
            return Insert(data, T->Left);
        else if (data>T->data)
            return Insert(data, T->Right);
    }
    return T;
}
void visit(Tree *t)
{
    printf("%d ", t->data);
}
void qx(Tree* t)
{
    if (t != NULL)
    {
        visit(t);
        qx(t->Left);
        qx(t->Right);
    }
}
void zx(Tree* t)
{
    if (t != NULL)
    {
        zx(t->Left);
        visit(t);
        zx(t->Right);
    }
}
void hx(Tree* t)
{
    if (t != NULL)
    {
        hx(t->Left);
        hx(t->Right);
        visit(t);
    }
}


void slove()
{
    Tree *tree;
    //tree = NULL;
    int n,tmp;

    while (~scanf("%d",&n))
    {
        tree = NULL;
        for (int i = 0; i < n; ++i)
        {
            scanf("%d", &tmp);
            Insert(tmp, tree);
        }

        qx(tree);
        printf("\n");
        zx(tree);
        printf("\n");
        hx(tree);
        printf("\n");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值