二叉搜索树

 题目描述:
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。
输入:
输入包含多行,每行一个字符串。
输出:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
样例输入:
10101
样例输出:
0 2
01 2
1 3
10 2
101 2

#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#include "string.h"

typedef struct{
	char ch[101];
	int value2;
	struct Node *left;
	struct Node *right;
}Node,*BiTree;

void insert(BiTree *b,char *ch2);
void find (BiTree b,char *ch,BiTree *b2);
void print (BiTree b);
char * copy (char *des,char *src,int start,int end);
void destroy (BiTree *b);

int main () {
	char ch[101];
	char ch2[101];
	BiTree b = NULL;
	
	int i,j,length;
	while (scanf ("%s",ch)!=EOF) {
		length = strlen (ch);
		for (i = 1;i <=length;i++){
			for (j = 0;j < length;j++) {
				if (j + i <= length) {
					copy (ch2,ch,j,j+i);
					insert (&b,ch2);
				}
				
			}
		}
	    print(b);
	destroy(&b);
	}

	return 0;
}


void insert (BiTree *b,char *ch2) {
	if (*b == NULL) {
		(*b) = (BiTree)malloc(sizeof(Node));
		strcpy((*b)->ch,ch2);
		(*b)->value2 = 1;
		(*b)->left = (*b)->right = NULL;
	}else {
		BiTree b2,b3;
		find (*b,ch2,&b2);
		if (b2 !=NULL) {
			b3= (BiTree)malloc(sizeof (Node));
		     b3->left = b3->right = NULL;
			 b3->value2 = 1;
			strcpy((b3)->ch,ch2);
			if (strcmp (b2->ch,ch2) > 0) {
				b2->left =  b3;
			}else {
				b2->right = b3;
			}
		}
	}
}


void find (BiTree b,char *ch,BiTree *b2) {
	if (b == NULL) {
		return;
	}else {
		if (strcmp(b->ch,ch) == 0) {
			b->value2++;
			*b2 = NULL;
			return;
		}else if (strcmp (b->ch,ch) > 0 ) {
			*b2 = b;
			find (b->left,ch,b2);
		}else {
			*b2 = b;
			find (b->right,ch,b2);
		}
	}
}



void print (BiTree b) {
	if (b == NULL) {
		return;
	}else {
		print(b->left);
		if (b->value2 >1) {
          printf("%s %d\n",b->ch,b->value2);
		}
		
		print(b->right);
	}
}


char * copy (char *des,char *src,int start,int end) {//不包括end的值
	int index = 0;
	for (;start < end;start++) {
		des[index++] = src[start];
	}
	des[index] = '\0';
}

void destroy (BiTree *b) {
	free(*b);
	*b= NULL;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值