测试样例
7
4 1 3 2 6 5 7
1 2 3 4 5 6 7
答案
2 3 1 5 7 6 4
#include<iostream>
using namespace std;
typedef struct BiTNode{
struct BiTNode *lchild;
struct BiTNode *rchild;
int data;
}BiTNode, *BiTree;
BiTree creatTree(int *in, int *pre, int n){
if(n <= 0)
return NULL;
else{
BiTree T = new BiTNode;
T->data = pre[0];
int i;
for(i = 0; i < n; i++){
if(pre[0] == in[i])
break;
}
T->lchild = creatTree(in, pre + 1, i);
T->rchild = creatTree(in + i + 1, pre + i + 1, n - i - 1);
return T;
}
}
void postorderTraversal(BiTree BT){
if(BT){
postorderTraversal(BT->lchild);
postorderTraversal(BT->rchild);
cout << " " << BT->data;
}
}
int main(){
int n;
cin >> n;
int in[32];
int pre[32];
BiTree T;
for(int i = 0; i < n; i++){
cin >> pre[i];
}
for(int i = 0; i < n; i++){
cin >> in[i];
}
T = creatTree(in, pre, n);
cout << "Postorder:";
postorderTraversal(T);
return 0;
}
模板
前序数组 pre【】
中序数组 in【】
node* create(int preL, int preR, int inL, int inR){
if(preL > preR){
return NULL;
}
node* root = new node;
root->data = pre[preL];
int k;
for(k = inL; k <= inR; k ++){
if(in[k] == pre[preL]){
break;
}
}
int numLeft = k - inL; //左子树节点个数
//左子树的先序区间为[prel + 1, preL + numLeft] 中序区间为[inL, k-1]
//返回左子树的根节点的根节点地址,赋值给root的左指针
root->lchild = create(preL + 1, preL + numLeftm, inL, k - 1);
//右子树的先序区间为[preL + numLeft + 1, preR], 中序区间为[k + 1, inR]
//返回右子树的根节点地址,赋值给root的右指针
root->rchild = create(preL + numLeft + 1, preR, k + 1, inR);
return root;
}