通过前序遍历和中序遍历构造二叉树,输出后序遍历第一个节点的值
//
// main.cpp
// PATA1138
//
// Created by Phoenix on 2018/2/26.
// Copyright © 2018年 Phoenix. All rights reserved.
//
#include <iostream>
#include <cstdio>
const int maxn = 50010;
int pre[maxn], in[maxn];
struct node {
int data;
node *lchild, *rchild;
};
node* newnode(int x) {
node* root = new node;
root->data = x;
root->lchild = root->rchild = NULL;
return root;
}
node* create(int preL, int preR, int inL, int inR) {
if(preL > preR) return NULL;
node* root = newnode(pre[preL]);
int k;
for(int i = inL; i <= inR; i++) {
if(in[i] == pre[preL]) {
k = i;
break;
}
}
root->lchild = create(preL + 1, preL + k - inL, inL, k - 1);
root->rchild = create(preL + k - inL + 1, preR, k + 1, inR);
return root;
}
int num = 0;
void postorder(node* root) {
if(root == NULL) return;
postorder(root->lchild);
postorder(root->rchild);
if(num == 0) printf("%d\n" ,root->data);
num++;
}
int main(int argc, const char * argv[]) {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", &pre[i]);
}
for(int i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
node* root = create(0, n - 1, 0, n - 1);
postorder(root);
return 0;
}