基数树实现位串的字典排序

按照基数树的定义,字符串的第一位如果是0,第一层的时候就向左转,第一位是1,第一层的时候就向右转。第二位是0,第二层的时候就向左转,第二位是1,第二层的时候就向右转。以此类推,按照输入构建出一棵树。我们可以用一个辅助字符串,remain。remain表示我们还剩下什么字符。假如我们要将011插入树中,刚开始的时候remain = “011”。然后因为remain[0]是0,所以先左转,remain = "11"。因为remain[0] = 1,向右转,remain = "1"。因为remain[0] = 1,所以向右转,remain = ""。这时remain = 0。如果这时候搜索到了一个不存在的点,就新创建一个节点,把节点的值赋值为“011”。如果现在搜索到的地方原来已经有节点了,就把节点的值赋值为“011”。不断地重复上述过程,一颗基数树就创建完了。至于怎么按照字典序输出呢?不难发现,只要按照前序遍历把这棵树输出就行了。下面是具体代码实现:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>

using namespace std;

typedef pair<int, int> pii;
typedef long long int LL;
const int INF = 0x3f3f3f3f;
const int maxn = 1000005;
int cnt = 0;
struct Node{
    char value[30];
    Node *lc, *rc;
    Node(){lc = rc = NULL;}
};

Node* Insert(Node *root, char *remain, char *used){//把x插入到搜索树中
    if (!root){
        Node *p = new Node();
        if (strlen(remain)){//搜索到不存在的点且remain不为空,就继续往下搜索
            strcpy(p->value, "haha");//如果当前节点只是搜索过程的中转站,也就是深色阴影的点,就赋值为haha作为区分
            int len = strlen(used);
            used[len] = remain[0];
            used[len + 1] = '\0';
            if (remain[0] == '0')
                p->lc = Insert(p->lc, remain + 1, used);
            else p->rc = Insert(p->rc, remain + 1, used);
        }else strcpy(p->value, used);//如果搜索到不存在的点,且remain为空。就可以创建节点赋值为used
        return p;
    }else{
        if (strlen(remain)){//如果搜索到一个本来就存在的点,且remain不为空,就继续往下搜索
            int len = strlen(used);
            used[len] = remain[0];
            used[len + 1] = '\0';
            if (remain[0] == '0') root->lc = Insert(root->lc, remain + 1, used);
            else root->rc = Insert(root->rc, remain + 1, used);
        }
        else strcpy(root->value, used);//如果搜索到本来存在的点,且remain为空,就给节点赋值为used
        return root;
    }
}

void Inorder_view(Node *root){
    if (root){
        if (strcmp(root->value, "haha"))
            cout << root->value << endl;
        if (root->lc) Inorder_view(root->lc);
        if (root->rc) Inorder_view(root->rc);
    }
}

int main()
{

    //freopen("1.txt", "r", stdin);
    char remain[30], used[30];
    Node *root = NULL;
    while (cin >> remain){
        strcpy(used, "");
        root = Insert(root, remain, used);
        cnt++;
    }
    Inorder_view(root);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值