题目: 根据先序遍历和中序遍历建立二叉树的二叉链表 并输出后序序列
思路:
- 根据先序序列确定根节点
- 在中序序列中找到根节点,将中序序列分成两段,前半段为根节点的左子树的中序序列,后半段为右子树的中序序列
- 递归直到每颗子树只有一个结点。
示例:
A
/ \
B C 先序序列:'A','B','D','E','C','F'
/ \ / 中序序列:'D','B','E','A','F','C'
D E F
//输出结果:
D
E
B
F
C
A
代码实现:
#include <iostream>
using namespace std;
typedef struct treenode{
char data;
struct treenode *lchild,*rchild;
}treenode, *tree;
int pos = 0;
tree build(char a[],char b[],int s,int e){
if(s<=e){
treenode *root = (treenode *)malloc(sizeof(treenode));
root->data=a[pos];
pos++;
int i;
for(i = s;i<=e;i++) if(b[i]==root->data) break;
root->lchild = build(a,b,s,i-1);
root->rchild = build(a,b,i+1,e);
return root;
}
return NULL;
}
void outs(tree t){
if(t){
outs(t->lchild);
outs(t->rchild);
cout<<t->data<<endl;
}
}
int main()
{
char A[] = {'A','B','D','E','C','F'};
char B[] = {'D','B','E','A','F','C'};
tree root=build(A,B,0,5);
cout<<"后序序列为:"<<endl;
outs(root);
return 0;
}