二叉樹生成,前序、中序、後序、層次遍歷的小例子!

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


char s[]="abd##e##c##";

int count=0;

typedef struct node
{
    char data;
    struct node *lchild,*rchild;
   
}NODE;

 

 

 

NODE *create()
{
    NODE *t;
    char a;
    a=s[count];
    count++;
    if(a=='#') t=NULL;
    else
    {
 t=(NODE *)malloc(sizeof(NODE));
 t->data=a;
 t->lchild=create();
 t->rchild=create();
    }
    return t;
   
}

void preorder(NODE *t)
{
    if (t!=NULL)
    {
 printf("%c/t",t->data);
 preorder(t->lchild);
 preorder(t->rchild);
    }
   
}

void inorder(NODE *t)
{
    if (t!=NULL)
    {
 inorder(t->lchild);
 printf("%c/t",t->data);
 inorder(t->rchild);
    }
   
}

void postorder(NODE *t)
{
    if (t!=NULL)
    {
 postorder(t->lchild);
 postorder(t->rchild);
 printf("%c/t",t->data);
    }
   
}

void PrintfTree(NODE *root)
{
  

    NODE *p_seq[80];
    int front,rear;
    front=rear=-1;
    int num=0;


    NODE *p_tree=root;

    if (p_tree==NULL)
    {
 return ;
    }

   
    rear=rear+1;
    p_seq[rear]=p_tree;
    num++;
   
 
    while(num!=0)
    {
 front=front+1;
 printf("%5c",p_seq[front]->data);
 num--;


 if(p_seq[front]->lchild!=NULL)
 {
     rear++;
     p_seq[rear]=p_seq[front]->lchild;
            num++;


 }
 if(p_seq[front]->rchild!=NULL)
 {
     rear++;
     p_seq[rear]=p_seq[front]->rchild;
            num++;

 }
    }
    printf("/n");

 

}

 

 

 

void main()
{
    NODE *t; 
    t=create();

   

   
    printf("先序遍歷樹");
    preorder(t);
    printf("/n");
   
    printf("中序遍歷樹");
    inorder(t); 
    printf("/n");
   
    printf("後序遍歷樹");
    postorder(t);
    printf("/n");

 

   printf("按層次遍歷樹");  

   PrintfTree(t);


  

   
   
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章