【BUCT数据结构类库】7.3--程序题--动态查找——二叉排序树实现

#include<iostream>
using namespace std;

//二叉排序树
typedef struct Node
{
    int key;
    Node *left;
    Node *right;
}*Tree;

Tree insert(Tree root, int key)
{
    if (root == NULL)
    {
        root = new Node;
        root->key = key;
        root->left = NULL;
        root->right = NULL;
        cout<<"插入函数中的root:    "<<root<<endl;
        //这里的root是指向根节点的指针 在递归中返回到上一层,不一定是主函数
        return root;
    }
    else if (key < root->key)
        root->left=insert(root->left, key);
    else
        root->right=insert(root->right, key);
}


//输出排序结果
void print(Node *root)
{
    if (root == NULL)
        return;
    print(root->left);
    cout << root->key << " ";
    print(root->right);
}

int main(){
    Tree root = NULL;
    int key;
    cout<<"请输入数据,输入-1结束"<<endl;
    while (cin >> key)
        if (key != -1)
            {root=insert(root, key); //这里不是每一次都要赋值,因为每次都是指向根节点的指针
            cout<<"主函数里的root:  "<<root<<endl;}
        else
            break;
    print(root);
    return 0;
}

运行结果

请输入数据,输入-1结束
1 2 4 24 6 5 4 3 2 55 6 4 3 24 6 -1
插入函数中的root:    0x1c1910
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c1960
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c1d40
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c1d90
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c3ef0
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c3f40
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c3f90
主函数里的root:  0x1c1910    
插入函数中的root:    0x1c3fe0
主函数里的root:  0x1c1910
插入函数中的root:    0x1c4030
主函数里的root:  0x1c1910
插入函数中的root:    0x1c4080
主函数里的root:  0x1c1910
插入函数中的root:    0x1c40d0
主函数里的root:  0x1c1910
插入函数中的root:    0x1c4120
主函数里的root:  0x1c1910
插入函数中的root:    0x1c4170
主函数里的root:  0x1c1910
插入函数中的root:    0x1c41c0
主函数里的root:  0x1c1910
插入函数中的root:    0x1c4210
主函数里的root:  0x1c1910
1 2 2 3 3 4 4 4 5 6 6 6 24 24 55

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半山乱步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值