SecondSearchOptionalTree

原创 2016年08月30日 11:57:40
#define N 9
#include<stdio.h>
#include<stdlib.h>
#include<stack>
struct ElemType{
	char key;
	int weight;
};
struct SSTable{
	ElemType *elem;
	int length;
};
typedef struct BiTNode{
	ElemType e;
	BiTNode* lchild;
	BiTNode* rchild;
}*SOSTree;
void CreateSSTable(SSTable &st,ElemType R[],int len){
	st.elem=(ElemType*)malloc(sizeof(ElemType)*(len+1));
	if(!st.elem){
		printf("内存分配失败\n");
		return;
	}
	st.length=len;
	for(int i=1;i<=len;i++)
		st.elem[i]=R[i-1];
}
void findSW(int sw[],SSTable st){
	sw[0]=0;
	for(int i=1;i<=st.length;i++)
		sw[i]=sw[i-1]+st.elem[i].weight;
}
bool Search(SOSTree T,int key){
	if(T==NULL)
		return false;
	while(T){
		if(T->e.key==key)
		{
			printf("%3c%3d\n",T->e.key,T->e.weight);
			return true;

		}
		if(T->e.key>key)
			T=T->lchild;
		else 
			T=T->rchild;
	}
	return false;
}
void SecondOptional(SOSTree &T,ElemType elem[],int sw[],int low,int high){
	int i=low;
	int min=abs(sw[high]-sw[low]);
	int dw=sw[high]+sw[low-1];
	for(int j=low+1;j<=high;j++){
		if(abs(dw-sw[j]-sw[j-1])<min){
			i=j;
			min=dw-sw[j]-sw[j-1];
		}
	}
	T=(BiTNode*)malloc(sizeof(BiTNode));
	T->e=elem[i];
	if(i==low)
		T->lchild=NULL;
	else SecondOptional(T->lchild,elem,sw,low,i-1);
	if(i==high)
		T->rchild=NULL;
	else SecondOptional(T->rchild,elem,sw,i+1,high);
}
void CreateSOSTable(SOSTree &T,SSTable st){
	int sw[N+1];
	if(st.length==0)
		T=NULL;
	else{
		findSW(sw,st);
		SecondOptional(T,st.elem,sw,1,st.length);
	}
}
void PreOrderTraverse(SOSTree T){
	std::stack<SOSTree> stack;
	while(T||!stack.empty()){
		if(T){
			printf("%3c%3d",T->e.key,T->e.weight);
			stack.push(T);
			T=T->lchild;
		}
		else{
			T=stack.top();
			stack.pop();
			T=T->rchild;
		}
	}
}
void main(){
	SSTable st={NULL,0};
	SOSTree T=NULL;
	char s;
	ElemType R[N]={{'A',1},{'B',1},{'C',2},{'D',5},{'E',3},{'F',4},{'G',4},{'H',3},{'I',5}};
	CreateSSTable(st,R,N);
	CreateSOSTable(T,st);
	PreOrderTraverse(T);
	printf("\n请输入要查找的元素\n");
	scanf("%c",&s);
	bool flag=Search(T,s);
	if(!flag) printf("查找关键字不存在");
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)