二叉树的建立与遍历

来源:互联网 发布:windows to go win8.1 编辑:程序博客网 时间:2024/05/29 21:36

问题描述:建立一棵二叉树,并对其进行遍历(先序、中序、后序),打印输出遍历结果。

基本要求:从键盘接受输入(先序),以二叉链表作为存储结构,建立二叉树(以先序来建立),并采用递归算法对其进行遍历(先序、中序、后序),将遍历结果打印输出。

测试数据:ABCффDEфGффFффф(其中ф表示空格字符)

则输出结果为先序:ABCDEGF

中序:CBEGDFA

后序:CGEFDBA

程序如下:

#include<stdio.h>

#include<stdlib.h>

typedef struct tnode

{

 char data;

 struct tnode *lchild;

 struct tnode *rchild;

 

}tnode;

tnode *Tree_creat(tnode *t)

{

 char ch;

 ch=getchar();

 if(ch==' ')

 t=NULL;

 else

 {

  if(!(t=(tnode *)malloc(sizeof(tnode))))

   printf("Error!");

  t->data=ch;//printf("[%c]",t->data);

  t->lchild=Tree_creat(t->lchild);

  t->rchild=Tree_creat(t->rchild);

  }

 return t;

}

 

void preorder(tnode *t)

{

 if(t!=NULL)

 {

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

  preorder(t->lchild);

  preorder(t->rchild);

 }

}

 

void Inorder(tnode *t)

{

 if(t!=NULL)

 {

  Inorder(t->lchild);

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

  Inorder(t->rchild);

 }

}

 

void postorder(tnode *t)

{

 if(t!=NULL)

 {

  postorder(t->lchild);

  postorder(t->rchild);

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

 }

}

 

void main()

{

 tnode *t=NULL;

 t=Tree_creat(t);

 preorder(t);

 printf("\n");

 Inorder(t);

 printf("\n");

 postorder(t);

 printf("\n");

}

 

原创粉丝点击