1、已知二叉树的先序遍历序列为A B D F E G H C,中序遍历序列为D F B G E H A C,构建二叉树并输出二叉树的后序遍历序列。
思想:
先序遍历二叉树的顺序为 根 左子树 右子树
中序遍历二叉树的顺序为 左子树、根、右子树;
首先根据二叉树的先序遍历序列确定二叉树的根,再根据中序遍历序列确定二叉树的左子树和右子树,再递归的对左子树和右子树进行以上操作。
代码如下:
# include<iostream>
using namespace std;
typedef struct BinNode{
char data;
BinNode *lchild,*rchild;
}bin_tree,*tree;
char pre_order[8]={'A','B','D','F','E','G','H','C'};
char mid_order[8]={'D','F','B','G','E','H','A','C'};
tree t;
BinNode *creat_tree(char *pre,char *mid,int n){
char *it_mid;
int left,right;
tree p;
if(n<=0)
return NULL;
p=new bin_tree;
if(!p)
exit(0);
else{
p->data=*pre;
if(*pre=='A')
t=p;
for(it_