用结构指针来动态建立树结构

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值