Sunday, December 23, 2007

特别提供数据结构中关于二叉树的代码

希望为广大被数据结构打蒙的同学提供一些帮助,这是我最近做数据结构时候自己写的,具体什么功能不用我说了吧,自己看吧……

//Creation & Traversion of a Binary Tree...DATA STRUCTURE. by ss1271@SIE,BUPT
#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct Node
{
 int data;
 struct Node *lchild, *rchild;
}BiTNode;
typedef BiTNode *BiTree;
int createBiTree(BiTree *T)
{
 char c;
 scanf("%c",&c);
 if (c==' ')
  *T=NULL;
 else
 {
  if(!(*T=(BiTNode*)malloc(sizeof(BiTNode))))
   return OVERFLOW;
  (*T)->data =c;
  createBiTree(&(*T)->lchild);
  createBiTree(&(*T)->rchild);
 }
 return OK;
}
//Traverse BinTree

void preordertraverse(BiTree T)
{
 if(T)
 {
  printf("%c",T->data);
  preordertraverse(T->lchild);
  preordertraverse(T->rchild);
 }
}
void inordertraverse(BiTree T)
{
 if(T)
 {
  inordertraverse(T->lchild );
  printf("%c",T->data );
  inordertraverse(T->rchild );
 }
}
void postordertraverse(BiTree T)
{
 if(T)
 {
  postordertraverse(T->lchild );
  postordertraverse(T->rchild );
  printf("%c",T->data );
 }
}
void destroyBiTree(BiTree T)
{
   if(T)
   {
     if(T->lchild)
       destroyBiTree(T->lchild);
     if(T->rchild)
       destroyBiTree(T->rchild);
     free(T);
     T=NULL;
   }
 }
void main()
{
 BiTree T=NULL;
 printf("Create Binary Tree(Use space to instead a null node).\n");
 createBiTree(&T);
 printf("This Binary Tree's Pre-Order Traversion is:\n");
 preordertraverse(T);
 printf("\nThis Binary Tree's In-Order Traversion is:\n");
 inordertraverse(T);
 printf("\nThis Binary Tree's Post-Order Traversion is:\n");
 postordertraverse(T);
 char m;
 printf("Destroy this Binary Tree?(Y/N):");
 if((m=getchar())=='Y')
  destroyBiTree(T);
 else
  exit(0);
}