二叉树

#include "stdio.h" #include "malloc.h"

#define maxsize 100

typedef int datatype;

typedef struct node {  datatype data;  struct node *Lchild,*Rchild; }BTNode;

void CreateBTNode(BTNode *&b,char *str) {  struct node *st[maxsize],*p=NULL;  int top=-1,k,j=0;  char ch;  b=NULL;  ch=str[j];  while(ch!='')  {   switch (ch)   {   case '(':    top++;    st[top]=p;    k=1;    break;   case ')':    top--;    break;   case ',':    k=2;    break;   default:    p=(BTNode*)malloc(sizeof(struct node));    p->data=ch;    p->Lchild=p->Rchild=NULL;             if(b==NULL)     b=p;    else    {     switch(k)     {     case 1:      st[top]->Lchild=p;                     break;     case 2:      st[top]->Rchild=p;      break;     }    }   }   j++;   ch=str[j];  } }

void InOrder(BTNode *b) {  if (b!=NULL)  {   InOrder(b->Lchild);   printf("%c ",b->data);   InOrder(b->Rchild);  } }

void PreOrder(BTNode *b) {  if (b!=NULL)  {   printf("%c ",b->data);   PreOrder(b->Lchild);   PreOrder(b->Rchild);  } } void main() {  struct node *st;  char *s="(D(B(A,C)E))";  CreateBTNode(st,s);  InOrder(st);  printf(" ");  PreOrder(st);  getchar(); }

原文地址:https://www.cnblogs.com/batman425/p/3347010.html