题目要求:给定一颗二叉树的先序序列和中序序列,建立二叉链表,输出后序
我的思路:由先序知道根结点,然后看中序,知道根结点的左右子树有哪些,然后递归实现
#include <stdio.h> #include<stdlib.h> #include<string.h> #define N 20 typedef char ElemType; char a[N],b[N]; typedef struct Node { ElemType data; struct Node *lchild,*rchild; } BiNode,*BiTree; void print(BiTree T); BiTree build(int qs,int zs,int len); int main() { while(scanf("%s %s",a,b)!=EOF) { BiTree t=build(0,0,strlen(a)); print(t); printf("\n"); } return 0; }
//建立二叉树 BiTree build(int qs,int zs,int len) //qs为前序数组的下标,zs为中序数组的下标 { if(len==0) return NULL; int i; BiTree t=(BiTree)malloc(sizeof(BiNode)); for(i=0; a[qs]!=b[zs+i]; i++); t->data=a[qs]; t->lchild=build(qs+1,zs,i); t->rchild=build(qs+i+1,zs+i+1,len-i-1); return t; }
//后序遍历 void print(BiTree T) { if(T==NULL) return ; print(T->lchild); print(T->rchild); printf("%c",T->data); }
测试数据: /*ABDGHCEIF GDHBAEICF */