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;
}*/

 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值