数据间隔符为空格,例如:ABC--DE-G--F--- -代表空格
- #include<stdio.h>
- #include<stdlib.h>
- #include<conio.h>
- typedef struct tree
- {
- char ch;
- struct tree *lchild;
- struct tree *rchild;
- }TREE;
- void createTree(TREE **bt);
- void fristRoot(TREE **bt);
- void middleRoot(TREE **bt);
- void lastRoot(TREE **bt);
- void destroyTree(TREE **bt);
- int main()
- {
- TREE **bt;
- printf("Pleas input string:\n");
- bt = (TREE **)malloc(sizeof(TREE *));
- createTree(bt);
- printf("\n先序:\n");
- fristRoot(bt);
- printf("\n中序:\n");
- middleRoot(bt);
- printf("\n后序:\n");
- lastRoot(bt);
- printf("\n");
- destroyTree(bt);
- free(bt);
- return 0;
- }
- void createTree(TREE **bt)
- {
- char ch;
- ch = getche();
- if(ch == ' ')
- *bt = NULL;
- else
- {
- *bt = (TREE *)malloc(sizeof(TREE));
- (*bt)->ch = ch;
- createTree(&((*bt)->lchild));
- createTree(&((*bt)->rchild));
- }
- }
- void fristRoot(TREE **bt)
- {
- if( *bt != NULL)
- {
- printf("%c ", (*bt)->ch);
- fristRoot(&((*bt)->lchild));
- fristRoot(&((*bt)->rchild));
- }
- }
- void middleRoot(TREE **bt)
- {
- if( *bt != NULL)
- {
- middleRoot(&((*bt)->lchild));
- printf("%c ", (*bt)->ch);
- middleRoot(&((*bt)->rchild));
- }
- }
- void lastRoot(TREE **bt)
- {
- if( *bt != NULL)
- {
- lastRoot(&((*bt)->lchild));
- lastRoot(&((*bt)->rchild));
- printf("%c ", (*bt)->ch);
- }
- }
- void destroyTree(TREE **bt)
- {
- if( *bt != NULL)
- {
- destroyTree( &((*bt)->lchild) );
- destroyTree( &((*bt)->rchild) );
- free(*bt);
- }
- }