A1138
个人思路
本题考查二叉树的遍历和重构
根据前序中序重构二叉树,后序遍历二叉树,输出第一个节点
一开始觉得5w数据量可能会超时,没想到暴力顺利AC
个人思路代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50010;
int N;
int pre[maxn], in[maxn];
struct Node{
int data;
int left, right;
Node(){}
Node(int d, int l, int r)
{
data = d;
left = l;
right = r;
}
}nodes[maxn];
int pos;
int newNode(int x)
{
nodes[pos] = Node(x, -1, -1);
return pos++;
}
void recreate(int &root, int preL, int preR, int inL, int inR)
{
if(preL > preR)
{
return;
}
root = newNode(pre[preL]);
int k;
for(k = inL; k < inR; ++k)
{
if(in[k] == pre[preL])
{
break;
}
}
int numleft = k - inL;
recreate(nodes[root].left, preL + 1, preL + numleft, inL, k - 1);
recreate(nodes[root].right, preL + numleft + 1, preR, k + 1, inR);
}
bool isEnd = false;
void postOrder(int root)
{
if(isEnd == true)
return;
if(root == -1)
return;
postOrder(nodes[root].left);
postOrder(nodes[root].right);
if(isEnd == false)
{
printf("%d", nodes[root].data);
isEnd = true;
}
}
int main(int argc, char *argv[]) {
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]);
}
int root = -1;
recreate(root, 0, N - 1, 0, N - 1);
postOrder(root);
return 0;
}
更优的解法
看到柳神有更精炼的代码,值得学习!,看来日后AC过后,还需要学习一下其他大神更优秀的代码
#include <iostream>
#include <vector>
using namespace std;
vector<int> pre, in;
bool flag = false;
void postOrder(int prel, int inl, int inr) {
if (inl > inr || flag == true) return;
int i = inl;
while (in[i] != pre[prel]) i++;
postOrder(prel+1, inl, i-1);
postOrder(prel+i-inl+1, i+1, inr);
if (flag == false) {
printf("%d", in[i]);
flag = true;
}
}
int main() {
int n;
scanf("%d", &n);
pre.resize(n);
in.resize(n);
for (int i = 0; i < n; i++) scanf("%d", &pre[i]);
for (int i = 0; i < n; i++) scanf("%d", &in[i]);
postOrder(0, 0, n-1);
return 0;
}