当前位置:编程学习 > C/C++ >>

C语言二叉树的建立,遍历(递归,非递归)

 

#include<stdio.h>

#include<stdlib.h>

#define MAXSIZE 20

typedef struct BiTnode{

 char data;

 struct BiTnode *lchild,*rchild;

}BiTnode,*BiTree;

 

//浜屽弶鏍戠殑閫掑綊寤虹珛

int i = 0;

BiTree Create(BiTree t,char s[])

{

 char ch;

 ch = s[i++];

 

 if(ch == ' ')

 {

  t = NULL;

 }

 else

 {

  if(!(t = (BiTree)malloc(sizeof(BiTnode))))

  {

   printf("fail to malloc!\n");

   exit(0);

  }

  else

  {

   t->data = ch;

   t->lchild = Create(t->lchild,s);

   t->rchild = Create(t->rchild,s);

  }

 }

 return t;

}

 

//涓簭閬嶅巻

/*

void display(BiTree t)

{

 BiTree stack[MAXSIZE],p;

 int top = -1;

 if(t)

 {

  p = t;

  while(top > -1 || p)

  {

   while(p)

   {   

    stack[++top] = p;

    p = p->lchild;

   }

   if(top > -1)

   {

    p = stack[top--];   

    printf("%c ",p->data);

    p = p->rchild;

   }

  }

  printf("\n");

 }

}

/*/

 

//鍓嶅簭閬嶅巻

/*

void display(BiTree t)

{

 BiTree stack[MAXSIZE],p;

 int top = -1;

 if(t)

 {

  p = t;

  while(top > -1 || p)

  {

   while(p)

   {

    printf("%c ",p->data);  

    stack[++top] = p;

    p = p->lchild;

   }

   if(top > -1)

   {

    p = stack[top--];       

    p = p->rchild;

   

   }

  }

  printf("\n");

 }

}

*//*

 

 

//鍓嶅簭閬嶅巻

void display(BiTree t)

{

     BiTree stack[MAXSIZE], p;

     int top = -1;

     if (t)

     {       

         stack[++top] = t;

         while (top > -1)

         {             

             p = stack[top--];

             printf("%c ", p->data);             

             if (p->rchild)

              {                 

                  stack[++top] = p->rchild;

              }             

             if (p->lchild)

              {                

                  stack[++top] = p->lchild;

              }

         }

         printf("\n");

     }

}*/

/*

//闈為€掑綊鍚庡簭閬嶅巻

void display(BiTree t)

{

 BiTree m,stack[MAXSIZE];

 int top = -1;

 int flag;

 if(t)

 {

loop:

  flag = 1;

  m = NULL;

  while(t)

  {

   stack[++top] = t;

   t = t->lchild;

  }

  while(flag)

  {

   t = stack[top];

   if(t->rchild == m)

   {

    printf("%c ",t->data);

    top--;

    m = t;

   }

   else

   {

    flag = 0;

    t = t->rchild;

   }

  }

  if(top>-1)

   goto loop;

 }

 

 printf("\n");

}

*/

 

//闈為€掑綊鍚庡簭閬嶅巻

void display(BiTree t)

{

    BiTree p = t, stack[MAXSIZE];

    int tag[MAXSIZE];

    int top = -1;

   

 do

     {

         while(p != NULL)

         {

             stack[++top] = p;

             tag[top] = 0;

             p = p->lchild;

         }            

         if(top > -1)

         {

             if(!tag[top]) 

              {

                  p = stack[top];

                  p = p->rchild;

                  tag[top] = 1;

              }

             else

              {           

   &nb

补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,