常用数据结构二叉树的建立(C语言+VC6.0平台)

二叉树是最重要的数据结构之一,先序建立二叉树的过程如下。

#include<stdio.h>

#include<stdlib.h>

typedef struct BiTNode

{

         char data;

         struct BiTNode *lchild,*rchild;

}BiTnode,*BiTree;

 

BiTree Create(BiTree root)//先序建立二叉树

{

         char ch;

         printf("input data:");

         root=(BiTree)malloc(sizeof(BiTnode));

         scanf("%c",&ch);

         getchar();

 

         if(ch=='#')

                  root=NULL;

         else

         {

                  root->data=ch;

                  root->lchild=Create(root->lchild);

                  root->rchild=Create(root->rchild);

         }

         return root;

}

 void PreOrderTra(BiTree root)

{

         if(root)

         {

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

                  PreOrderTra(root->lchild);

                  PreOrderTra(root->rchild);

         }

}

 void InOrderTra(BiTree root)

{

         if(root)

         {

                  InOrderTra(root->lchild);

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

                  InOrderTra(root->rchild);

         }

}

 void LastOrderTra(BiTree root)

{

         if(root)

         {

                  LastOrderTra(root->lchild);

                  LastOrderTra(root->rchild);

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

         }

}

int main(void)

{

         BiTree root=0;

         root=Create(root);

         printf("先序遍历:");

         PreOrderTra(root);

         printf("\n");

         printf("中序遍历:");

         InOrderTra(root);

         printf("\n");

         printf("后序遍历:");

         LastOrderTra(root);

         printf("\n");

         return 0; 

}

posted @ 2015-05-19 21:28  pctech  阅读(281)  评论(0编辑  收藏  举报