二叉树的递归遍历(先序,中序,后序)

来源:互联网 发布:网络汇聚层 编辑:程序博客网 时间:2024/05/16 20:29
#include "stdio.h"#include "malloc.h"#define M 100typedef struct node{  /* 采用二叉链表存储结构 */   char data;   struct node *lchild,*rchild;}BTnode;BTnode *create()/*利用先序遍历的过程创建二叉树*/{ BTnode *t; char ch; scanf("%c",&ch); if(ch=='#')  t=NULL;  else   {t=(BTnode *)malloc(sizeof(BTnode)) ;    t->data=ch;    t->lchild=create();    t->rchild=create();    }  return t;}void preorder(BTnode *t)/*先序遍历二叉树*/{ if(t!=NULL) printf("%c ",t->data); if(t->lchild!=NULL) preorder(t->lchild); if(t->rchild!=NULL) preorder(t->rchild);}void inorder(BTnode *t)/*中序遍历二叉树*/{  if(t!=NULL)  {    if(t->lchild!=NULL)    inorder(t->lchild);    printf("%c ",t->data);    if(t->rchild!=NULL)    inorder(t->rchild);  }}void postorder(BTnode *t)/*后序遍历二叉树*/{  if(t!=NULL)  { if(t->lchild!=NULL)    postorder(t->lchild);    if(t->rchild!=NULL)    postorder(t->rchild);    printf("%c ",t->data);  }}void main(){BTnode *t;printf("Input data:") ;t=create();printf("==================The result==========================\n");printf("The preorder is:\n");preorder(t);printf("\n");printf("The inorder is:\n");inorder(t);printf("\n");printf("The postorder is:\n");postorder(t);printf("\n");}

0 0
原创粉丝点击