#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct TreeNode { int count; char val; // 0-左 1-右 struct TreeNode* left; //左节点-0 struct TreeNode* right; //右节点-1 } TNode; void printTree(char* t, TNode* root) { //前序遍历打印二叉树 if (root) { if (root->count > 1) { //输出t中的所有字符,并且打印本次遍历的字符 printf("%s%c %d\n", t, root->val, root->count); } int length = 0; for (int i = 0; t[i] != '\0'; i++) { length++; } t[length] = root->val; printTree(t, root->left); printTree(t, root->right); t[length] = '\0'; //剪枝 } } void getSubParam(char s[]) { //构建一颗二叉树,字典树 TNode* initNode = (TNode*)malloc(sizeof(TNode)); //创世块 int length = 0; while (s[length] != '\0') { length++; } for (int i = 0; i < length; i++) { TNode* tmp = initNode; for (int j = i; j < length; j++) { //双重循环 if (s[j] == '0') { if (!tmp->left) { //没有左孩子,手动申请一个空间放左孩子 tmp->left = (TNode*)malloc(sizeof(TNode)); tmp->left->val = '0'; tmp->left->count = 0; } tmp->left->count++; tmp = tmp->left; } if (s[j] == '1') { if (!tmp->right) { tmp->right = (TNode*)malloc(sizeof(TNode)); tmp->right->val = '1'; tmp->right->count = 0; } tmp->right->count++; tmp = tmp->right; } } } char* tmp1 = (char*)malloc(sizeof(char) * 101); char* tmp2 = (char*)malloc(sizeof(char) * 101); printTree(tmp1, initNode->left); printTree(tmp2, initNode->right); } //字典二叉树 int main() { char s[100]; // FILE* fp = fopen("./data.in", "r"); while (scanf("%s\n", s) != EOF) { getSubParam(s); } }