已知二叉树的中序和前序求后序
已知:
中序:dgbaechf 前序:adbgcefh
思路:
前序遍历的第一个元素是根节点a,然后查找中序中a的位置,把中序遍历分为 dgb a echf,而因为节点个数要对应,
则把前序遍历分为a dbg cefh,dbg为左子树,cefh为右子树,即可递归下去。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 // 二叉树节点结构 6 typedef struct bitnode 7 { 8 char data; // 节点存储的数据 9 struct bitnode *lchild; // 左孩子 10 struct bitnode *rchild; // 右孩子 11 }bitnode,*bitree; 12 13 // 前序遍历 14 void pre_sequence(bitree t) 15 { 16 if (t == NULL){ 17 return; 18 } 19 printf("%c",t->data); 20 pre_sequence(t->lchild); 21 pre_sequence(t->rchild); 22 } 23 // 中序遍历 24 void mid_sequence(bitree t) 25 { 26 if(t == NULL){ 27 return; 28 } 29 mid_sequence(t->lchild); 30 printf("%c",t->data); 31 mid_sequence(t->rchild); 32 } 33 // 后序遍历 34 void bak_sequence(bitree t) 35 { 36 if(t == NULL){ 37 return; 38 } 39 bak_sequence(t->lchild); 40 bak_sequence(t->rchild); 41 printf("%c",t->data); 42 } 43 44 // 已知前序遍历和中序遍历,建树 45 bitree create_tree(char *pre, char *in, int len) 46 { 47 if (len <= 0){ 48 return NULL; 49 } 50 int i; 51 bitree root; 52 root = (bitnode *)malloc(sizeof(bitnode)); 53 root->data = pre[0]; 54 for (i=0; ;i++){ // 找到中序遍历中根的位置 55 if (in[i] == pre[0]){ 56 break; 57 } 58 } 59 root->lchild = create_tree(pre+1,in,i); 60 root->rchild = create_tree(pre+i+1,in+i+1,len-i-1); 61 return root; 62 } 63 64 int main(void) 65 { 66 bitree root; 67 char pre[50]; 68 char in[ 50] ; 69 printf("please input pre_sequence:"); 70 scanf("%s",pre); 71 printf("please input mid_sequence:"); 72 scanf("%s",in); 73 74 /* 建树 */ 75 root = create_tree(pre,in,strlen(pre)); 76 77 printf(" 前序遍历结果: "); 78 pre_sequence(root); 79 printf(" 中序遍历结果: "); 80 mid_sequence(root); 81 printf(" 后序遍历结果: "); 82 bak_sequence(root); 83 printf(" "); 84 return 0; 85 }