05年華中科大機試第三題(輸入一個字符串,建立一個二叉排序樹,並中序遍歷輸出)

/*第三題:輸入一個字符串,建立一個二叉排序樹,並中序遍歷輸出;*/

/*這裏採用了兩種遍歷,此處是非遞歸。下面註釋的是遞歸*/
/*測試數據: poiuyt    輸出數據;i o p t u y   
  測試數據: 621345     輸出數據: 1 2 3 4 5 6*/
/*程序:*************************愛X的味道 07級華中農業大學計算機系*****************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50
typedef struct Node
{
	char data;
	struct Node *Lchild;
	struct Node *Rchild;
}Node,*BiTree;

typedef struct 
{
	BiTree elem[MAX];
	int top;
}Stack;  
void InitStack(Stack *s)
{
	s->top=-1;
}
int Push(Stack *s,BiTree *T)
{
	if(s->top>MAX-1) return 0;
	s->top++;
	s->elem[s->top]=(*T);
	return 1;
}
int Pop(Stack *s,BiTree *T)
{
	if(s->top<-1) return 0;
    *T=s->elem[s->top];   
	s->top--;
	return 1;
}
int IsEmpty(Stack s)
{
	if(-1==s.top)
		return 1;
	else
		return 0;
}
void InsertSortTree(BiTree *tree, char key)
{
	BiTree T;
	if(*tree == NULL)
	{
		T=(BiTree)malloc(sizeof(Node));
		T->data=key;
		T->Lchild=NULL;
		T->Rchild=NULL;
		*tree=T;
	}
	else
		if((*tree)->data>key)
			InsertSortTree(&((*tree)->Lchild),key);
		else
			if((*tree)->data<key)
				InsertSortTree(&((*tree)->Rchild),key);
}
void CreateSortTree(BiTree  *tree,char *str )
{
	*tree=NULL;
	int i=0;
	while(str[i]!='\0')
	{
		InsertSortTree(&(*tree),str[i]);
		i++;
	}
}

void InOrdTree(BiTree T)    
{
	Stack s;
	BiTree p=T;
	InitStack(&s);
	while(p!=NULL || !IsEmpty(s))
	{
		if(p!=NULL)
		{
			Push(&s,&p);
			p=p->Lchild;
		}
		else
		{
			Pop(&s,&p);
			printf(" %c ",p->data);
			p=p->Rchild;
		}
	}
	printf("\n\n");
}
int main()
{
	char str[100]="\0";
	BiTree tree;
	printf("請輸入一個字符串:\n\n");
	gets(str);
	CreateSortTree(&tree,str);
	printf("中序遍歷的結果是:\n\n");
    InOrdTree(tree);
	printf("\n\n");
	return 0;
}

/*
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node
{
	char data;
	struct Node *Lchild;
	struct Node *Rchild;
}Node,*BiTree;
void InsertSortTree(BiTree *tree, char key)
{
	BiTree T;
	if(*tree == NULL)
	{
		T=(BiTree)malloc(sizeof(Node));
		T->data=key;
		T->Lchild=NULL;
		T->Rchild=NULL;
		*tree=T;
	}
	else
		if((*tree)->data>key)
			InsertSortTree(&((*tree)->Lchild),key);
		else
			if((*tree)->data<key)
				InsertSortTree(&((*tree)->Rchild),key);
}
void CreateSortTree(BiTree  *tree,char *str )
{
	*tree=NULL;
	int i=0;
	while(str[i]!='\0')
	{
		InsertSortTree(&(*tree),str[i]);
		i++;
	}
}

void InOrdTree(BiTree  tree)
{
	if(tree !=NULL)
	{
	InOrdTree(tree->Lchild);
	printf(" %c ",tree->data);
	InOrdTree(tree->Rchild);
	}
}

int main()
{
	char str[100]="\0";
	BiTree tree;
	printf("請輸入一個字符串:\n\n");
	gets(str);
	CreateSortTree(&tree,str);
	printf("中序遍歷的結果是:\n\n");
    InOrdTree(tree);
	printf("\n\n");
	return 0;
}*/

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章