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