/**
* StructTreePoint.c
* version 1.0 2006-9-18
* write by jsp
* 用结构指针来动态建立树结构
*/
#include"stdio.h"
#include"stdlib.h"
int count = 0;
//输入数据
int *input(int *inputData)
{
int *pc;
int data;
pc = (int *)malloc(sizeof(int));
do
{
if(pc == NULL)
{
printf("CREAT FAIL!!/n");
if(count == 0)
return NULL;
else
return inputData;
}
scanf("%d",&data);
if(data != 0)
{
*pc = data;
if(count == 0)
inputData = pc;
count ++;
pc++;
}
}while(data != 0);
return inputData;
}
struct LpTree
{
struct LpTree * left;
struct LpTree * right;
int data;
};
//前序遍历
void preOrder(struct LpTree *pTreeC)
{
if(pTreeC != NULL );
{
printf("%d/n",pTreeC->data);
if(pTreeC->left != NULL)
preOrder(pTreeC->left);
if(pTreeC->right != NULL)
preOrder(pTreeC->right);
}
}
//中序遍历
void midOrder(struct LpTree *pTreeC)
{
if(pTreeC != NULL );
{
if(pTreeC->left != NULL)
midOrder(pTreeC->left);
printf("%d/n",pTreeC->data);
if(pTreeC->right != NULL)
midOrder(pTreeC->right);
}
}
//后序遍历
void bakOrder(struct LpTree *pTreeC)
{
if(pTreeC != NULL );
{
if(pTreeC->left != NULL)
bakOrder(pTreeC->left);
if(pTreeC->right != NULL)
bakOrder(pTreeC->right);
printf("%d/n",pTreeC->data);
}
}
struct LpTree *creat(struct LpTree *pTree,int *inD)
{
struct LpTree * pc, *pf;
int i;
pc = (struct LpTree *)malloc(sizeof(struct LpTree));
if(pc == NULL)
{
return NULL;
}
pc ->data = *inD;
pc ->left = NULL;
pc ->right = NULL;
pTree = pc;
pc = NULL;
for(i = 1 ; i < count; i++)
{
pf = pTree;
inD++;
pc = (struct LpTree *)malloc(sizeof(struct LpTree));
pc ->data = *inD;
pc ->left = NULL;
pc->right = NULL;
while(pf != NULL)
{
if(pc->data < pf->data)//判断是否是左子树
{
if(pf->left == NULL)
{
pf->left = pc;
break;
}
else
{
pf = pf->left;
}
}
else
{
if(pf->right == NULL)//判断是否是右子树
{
pf->right=pc;
break;
}
else
{
pf=pf->right;
}
}
}
}
return pTree;
}
void main()
{
int *inputData = NULL;
int *inputDataC;
struct LpTree *pTree = NULL;
struct LpTree *pTreeC;
int i;//循环变量
inputData = input(inputData);//输入数据
inputDataC = inputData;
// 打印输入的数据出和相对应的地址
for(i = 0 ; i < count ; i++)
{
printf("%d--%d/n",inputDataC,*inputDataC);
inputDataC++;
}
inputDataC = inputData;
pTree = creat(pTree,inputDataC);
pTreeC=pTree->left;
printf("打印出左子树木:/n");
while(pTreeC != NULL)
{
printf("%d--%d/n",pTreeC,pTreeC->data);
pTreeC=pTreeC->left;
}
pTreeC=pTree->right;
printf("打印出右子树木:/n");
while(pTreeC != NULL)
{
printf("%d--%d/n",pTreeC,pTreeC->data);
pTreeC=pTreeC->right;
}
printf("前序遍历:/n");
pTreeC=pTree;
preOrder(pTreeC);
printf("中序遍历:/n");
pTreeC=pTree;
midOrder(pTreeC);
printf("后序遍历:/n");
pTreeC=pTree;
bakOrder(pTreeC);
}