按照基数树的定义,字符串的第一位如果是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;
}