牛客网 KY223 二叉排序树

该代码展示了如何使用C++实现二叉排序树的数据结构,包括插入节点、前序、中序和后序遍历功能。程序通过`insert`函数将整数插入树中,然后分别通过`front`、`mid`和`back`函数进行遍历输出。
摘要由CSDN通过智能技术生成

链接: KY223 二叉排序树

#include <iostream>
#include <cstring>
using namespace std;
const int N=110;
int h, e[N], l[N], r[N], idx;

void insert(int x) {
    e[idx]=x;
    if (h==-1) {
        h=idx++;
        return;
    }

    //找到要插入位置的父节点p
    int p=0, q=h; 
    while (q!=-1) {
        p=q;
        int j=e[q];
        if (x==j) return;
        else if (x<j) q=l[q];
        else q=r[q];
    }
    if (x<e[p]) l[p]=idx++;
    else r[p]=idx++;
}

void front(int h) {   //前序遍历
    if (h==-1) return;
    cout<<e[h]<<" ";
    front(l[h]);
    front(r[h]);
}

void mid(int h) {   //中序遍历
    if (h==-1) return;
    mid(l[h]);
    cout<<e[h]<<" ";
    mid(r[h]);
}

void back(int h) {   //后序遍历
    if (h==-1) return;
    back(l[h]);
    back(r[h]);
    cout<<e[h]<<" ";
}

void init () {
    h=-1, idx=0;
    memset(e, 0, sizeof e);
    memset(l, -1, sizeof l);
    memset(r, -1, sizeof r);
}

int main() {
    int n;
    while (cin>>n) {
        init();
        while (n--) {
            int x;
            cin>>x;
            insert(x);
        }
        front(0); cout<<endl;
        mid(0); cout<<endl;
        back(0); cout<<endl;
    }
    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值