完全二叉树的创建,循环方式创建

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
 int data;
 struct Node *LTree,*RTree;
}BiTree;

typedef struct Stack
{
 BiTree *StackValue;
 struct Stack *pStackNext;
}STACK;


BiTree* createBiTree()
{
 BiTree *pTreeHead = NULL,
  *pTree = NULL,
      *newNode = NULL ;
 int i = 0, myarray[10] = {1,2,3,4,5,6,7,8,9};

 for(i = 0;i< 10;i++)
 {
  newNode = (BiTree*)malloc(sizeof(BiTree));
  newNode ->data = myarray[i];
  newNode ->LTree = NULL;
  newNode ->RTree = NULL;

  if(!pTreeHead)
  {
   pTreeHead = pTree = newNode;
  }
  else
  {
   pTree ->LTree = newNode;
   newNode ->RTree= pTree;
   pTree = newNode;
  }
 }
 return pTreeHead;
}

BiTree * CreateBiTree()
{
 BiTree *pHead [10] ;
 int index =0,myarray[10] = {0,1,2,3,4,5,6,7,8,9};

 for(index = 0;index <10; index ++)
 {
  pHead [index] = (BiTree*)malloc(sizeof(BiTree));
  pHead [index] ->data = myarray[index];
  pHead [index] ->LTree = NULL;
  pHead [index] ->RTree = NULL;
 }
 free(pHead [0]);

 for(index = 1;index < 10; index ++)
 {
  if(2*index <10)
  {
   pHead [index] ->LTree = pHead [2*index];
  }
  else
  {
   pHead [index] ->LTree  =NULL;
  }

  if(2*index +1 < 10)
  {
   pHead [index] ->RTree = pHead [2*index +1];
  }
  else
  {
   pHead [index] ->RTree = NULL;
  }
  
 }
 return pHead[1];
}


void push_head(STACK **pStackHead,BiTree *newNode)
{
 STACK *temp = (STACK*)malloc(sizeof(STACK));
 temp ->StackValue = newNode;
 temp ->pStackNext = (*pStackHead);
 (*pStackHead) = temp;
}

BiTree* pop_head(STACK **pStackHead)
{
 if(!(*pStackHead))
 {
  return NULL;
 }
 else
 {
  STACK *temp = (*pStackHead);
  BiTree *TREE = temp ->StackValue;
  (*pStackHead) = (*pStackHead) ->pStackNext;
  free(temp);
  return TREE;
 }
}


void Hou(BiTree *pTHead)
{
 STACK *pSHead = NULL;
 BiTree *Ji = NULL;
 if(pTHead)
 {
  push_head(&pSHead,pTHead);
  pTHead = pTHead ->LTree;
 }
 while(pSHead)
 {
  while(pTHead)
  {
   push_head(&pSHead,pTHead);
   pTHead = pTHead ->LTree;
  }

  if(pSHead ->StackValue ->RTree == NULL  || Ji == pSHead ->StackValue ->RTree)
  {
   Ji = pop_head(&pSHead);
   printf("%d",Ji->data);
  }
  else
  {
   pTHead = pSHead ->StackValue ->RTree;
  }
 }
}

void Qian(BiTree *pTHead)
{
 STACK *stack = NULL;
 while(true)
 {
  while(pTHead)
  {
   printf("%d ",pTHead ->data);
   push_head(&stack,pTHead); 
   pTHead = pTHead ->LTree;
  }
  pTHead = pop_head(&stack);
  if(!pTHead)
  {
   break;
  }
  pTHead = pTHead ->RTree;
 }
}

int main()
{
 BiTree *pHead = NULL;
 pHead = CreateBiTree();
 Qian(pHead);
 
 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值