利用c++代码实现输入格式: 两行。第一行是二叉树的前序遍历序列,第二行是中序遍历序列。每个数字表示的结点之间用空格隔开。 输出格式: 一行。由输入中的前序列和中序遍历序列重建的二叉树的后序遍历序列。每个数字表示的结点之间用空格隔开
时间: 2023-05-30 14:02:48 浏览: 374
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode *BinTree;
struct TreeNode{
int Data;
BinTree Left;
BinTree Right;
};
BinTree CreateBinTree(int *pre, int *in, int n){
if(n == 0) return NULL;
int i;
BinTree T = (BinTree)malloc(sizeof(struct TreeNode));
T->Data = pre[0];
for(i = 0; i < n; i++){
if(in[i] == pre[0]) break;
}
T->Left = CreateBinTree(pre + 1, in, i);
T->Right = CreateBinTree(pre + i + 1, in + i + 1, n - i - 1);
return T;
}
void PostorderTraversal(BinTree BT){
if(BT){
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf("%d ", BT->Data);
}
}
int main(){
int n, i;
scanf("%d", &n);
int *pre = (int*)malloc(sizeof(int) * n);
for(i = 0; i < n; i++){
scanf("%d", &pre[i]);
}
int *in = (int*)malloc(sizeof(int) * n);
for(i = 0; i < n; i++){
scanf("%d", &in[i]);
}
BinTree BT = CreateBinTree(pre, in, n);
PostorderTraversal(BT);
return 0;
}
阅读全文