二叉树的建立(广义表)及3种遍历

时间:2022-02-20 19:30:56

/*****************************************************
  Copyright (C)
  FileName: BiTree.c
  Author: Luqing             Date:2006/4/11
  Description:     //  The basic  operations of  Bi_Tree    
  Version:         // v1.0
  Function List:   // creatree,  preorder, inorder, postorder
******************************************************/
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef char ElemType;
typedef struct node
{
 ElemType data;
 struct node *left,*right;
} BiTreeNode,*BiTree;

struct node * creatree(char *str)
{
 BiTreeNode *stack[MaxSize],*p;
 BiTreeNode *BT;
 int top=-1,k,j=0;//top为栈指针,k指定是左还是右孩子,j为str指针
 char ch;
 BT=NULL;
 ch=str[j];
 while (ch!='/0')
 {
  switch(ch)
  {
  case '(':top++;stack[top]=p;k=1;  //为左结点
   break;
  case ')':top--;
   break;
  case ',':k=2;   //为右结点
   break;
  default: p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
   p->data=ch;p->left=p->right=NULL;
   if (BT==NULL) //根结点//
    BT=p;
   else
   {
    switch(k)
    {
    case 1:stack[top]->left=p;
     break;
    case 2:stack[top]->right=p;
    }
   }
  }
  j++;
  ch=str[j];
 }
 return BT;
}
void preorder(BiTreeNode *BT)
{
 if (BT!=NULL)
 {
  printf("%c",BT->data);
  preorder(BT->left);
  preorder(BT->right);
 }
}
void inorder(BiTreeNode *BT)
{
 if (BT!=NULL)
 {
  inorder(BT->left);
  printf("%c",BT->data);
  inorder(BT->right);
 }
}
void postorder(BiTreeNode *BT)
{
 if (BT!=NULL)
 {
  postorder(BT->left);
  postorder(BT->right);
  printf("%c",BT->data);
 }
}

int main()
{
 BiTreeNode *B;
 //char *s="A(B,C)";
 char *s="A(B(E,F),C(D(G,),)";
 B=creatree(s);
 printf("/n前序遍历:");
 preorder(B);
 printf("/n中序遍历:");
 inorder(B);
 printf("/n后序遍历:");
 postorder(B);
 printf("/n");
 
 return 0;
}