Description
已知一棵二叉树的前序序列和中序序列分别存于两个一维数组中,试编写算法建立该二叉树的二叉链表。
Input
分两行分别输入一棵二叉树的前序序列和中序序列。
Output
输出该二叉树的后序序列。
-
Sample Input
ABDFGCEH BFDGACEH
-
Sample Output
FGDBHECA
#include<stdio.h> #include<stdlib.h> typedef struct BTNode{ char data; struct BTNode *lchild; struct BTNode *rchild; }BTNode; char pre[100], mid[100]; int len; void init(){ int i; char s; for(i = 0; i < 100; i++){ pre[i] = '#'; mid[i] = '#'; } i = 0; while(scanf("%c",&s) && s!='\n'){ pre[i] = s; i++; } i = 0; while(scanf("%c",&s) && s!='\n'){ mid[i] = s; i++; } i = 0; while(pre[i]!='#'){ i++; } len = i; } BTNode *CreateNode(int pre_start, int pre_end, int mid_start, int mid_end){ int i, LLen,RLen; BTNode *root = (BTNode*)malloc(sizeof(BTNode)); root->data = pre[pre_start]; root->lchild = NULL; root->rchild = NULL; i = mid_start; while(root->data != mid[i]) i++; LLen = i - mid_start; RLen = mid_end - i; if(LLen){ root->lchild = CreateNode(pre_start+1, pre_start+LLen, mid_start, i-1); } if(RLen){ root->rchild = CreateNode(pre_start+LLen+1, pre_end, i+1,mid_end); } return root; } void PrintfTree(BTNode *root){ if(root->lchild) PrintfTree(root->lchild); if(root->rchild) PrintfTree(root->rchild); printf("%c",root->data); } int main(){ BTNode *root = (BTNode*)malloc(sizeof(BTNode)); init(); root = CreateNode(0 , len-1, 0, len-1); PrintfTree(root); return 0; }
题解:先序和中序可确定唯一二叉树,后序和中序可确定唯一二叉树,先序和后序不可确定唯一二叉树。先序的第一个元素A及根节点,找到该元素对应在中序序列中的A1,A1左边即为根节点左子树上的全部元素,A1右边即为根节点右子树上的全部元素。以此类推,找出所有根节点。