(p171)基数树

思路很简单,把浅深色的节点设为1,其余的设为0,先序遍历用s存储当前路径对应的字符串,遇到1输出即可

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 100
struct node{
	int f;
	struct node *l,*r;
};
void insert(struct node *root,char s[],int dep)
{
	struct node *new;
	if (dep==strlen(s))
		root->f=1;
	else
		if (s[dep]=='0')
		{
			if (root->l==NULL)
			{
				new=(struct node *)malloc(sizeof(struct node));
				new->l=NULL;
				new->r=NULL;
				new->f=0;
				root->l=new;
				insert(new,s,dep+1);
			}
			else
				insert(root->l,s,dep+1);
		}
		else
		{
			if (root->r==NULL)
			{
				new=(struct node *)malloc(sizeof(struct node));
				new->l=NULL;
				new->r=NULL;
				new->f=0;
				root->r=new;
				insert(new,s,dep+1);
			}
			else
				insert(root->r,s,dep+1);
		}
}
void print(char s[],int l)
{
	int i;
	for (i=0;i<l;i++)
		printf("%c",s[i]);
	printf("\n");
}
void sort(struct node *root,char s[],int dep)
{
	if (root->f==1)
		print(s,dep);
	if (root->l!=NULL)
	{
		s[dep]='0';
		sort(root->l,s,dep+1);
	}
	if (root->r!=NULL)/*回溯*/
	{
		s[dep]='1';
		sort(root->r,s,dep+1);
	}
}
int main(void)
{
	int n,i;
	char s[max];
	struct node *root;
	root=(struct node *)malloc(sizeof(struct node));
	root->f=0;
	root->l=NULL;
	root->r=NULL;
	scanf("%d",&n);
	for (i=0;i<n;i++)
	{
		scanf("%s",s);
		insert(root,s,0);
	}
	sort(root,s,0);
	return 0;
}


好的,我可以帮你修改代码。首先,我需要了解您的代码和数据结构。 链式基数排序是一种基于位运算的排序算法,其核心思想是将待排序的元素按照不同的位分别进行排序,最终得到有序的序列。在实现链式基数排序时,我们需要使用一个链式结构来存储元素,这个链式结构通常是一个链表或者。 在您的代码中,可能是由于数据类型不当或者数据溢出等问题导致了错误。为了解决这个问题,您可以尝试以下几个方法: 1. 检查数据类型:确保您使用的数据类型能够正确地表示待排序的元素,例如使用 long long 类型代替 int 类型。 2. 检查数据范围:如果您的数据超出了数据类型的表示范围,您需要使用更大的数据类型或者使用其他方法来处理超出范围的数据。 3. 检查算法实现:确保您的算法实现正确,没有逻辑错误或者语法错误。 以下是一个简单的链式基数排序的代码实现,您可以参考一下: ```c++ #include <iostream> #include <cstring> using namespace std; const int maxn = 100005; const int maxd = 10; struct Node { int val; Node *next; } *head[maxd], *tail[maxd]; int n; void radix_sort() { for (int i = 0; i < maxd; i++) { head[i] = tail[i] = NULL; } for (int i = 1; i <= n; i++) { Node *p = new Node(); cin >> p->val; p->next = NULL; int d = p->val % 10; if (head[d] == NULL) { head[d] = tail[d] = p; } else { tail[d]->next = p; tail[d] = p; } } for (int d = 1; d < maxd; d++) { if (head[d] == NULL) { continue; } Node *p = head[d]; while (p != NULL) { cout << p->val << " "; p = p->next; } } } int main() { cin >> n; radix_sort(); return 0; } ``` 这个实现比较简单,只是按照个位数进行了排序,您可以根据需要进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值