二叉树的建立以及先序,中序,后序遍历

来源:互联网 发布:河南坠子乎延庆打擂 编辑:程序博客网 时间:2024/06/02 07:17
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按前序中序后序
#include<stdio.h>#include<stdlib.h>#include<string.h>#define N 51typedef struct Bintree{char data;struct Bintree *lchild,*rchild; }Bintree,*Bin;char a[N];int i=-1;Bin creat() //结构体指针类型  还可以Bintree *creat() {Bintree *T; if(a[++i]!=',') { T=(Bintree*)malloc(sizeof(Bintree)); T->data =a[i]; T->lchild=creat(); T->rchild=creat(); return T;  } else {  return NULL; }}void preorder(Bintree*T){if(T){printf("%c",T->data);preorder(T->lchild);preorder(T->rchild);}}void inorder(Bintree *T){  if(T)   {    inorder(T->lchild );printf("%c",T->data );inorder(T->rchild );   }   }void finorder(Bintree *T){  if(T)   {    finorder(T->lchild );finorder(T->rchild );printf("%c",T->data );   }  }int main(){Bintree *T;gets(a); T=creat();//建立二叉树  preorder(T); printf("\n"); inorder(T); printf("\n"); finorder(T); printf("\n"); } 

方式遍历该二叉树。
阅读全文
0 0
原创粉丝点击