1.题目
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
2.题目分析
法一:在左子树遍历就在左子树查找,每查找一个节点就把它标记,最后在中序遍历中两边都被标记的节点就输出(在边界的只看一边)
法二:先序中序转后序,转后输出第一个节点。加上flag防止超时
3. 代码
法一:
#include<iostream>
#include<unordered_map>
using namespace std;
int in[50010], pre[50010],mark[1000000];//mark大点防止段错误
unordered_map<int, int> pos;//记录节点在in中序遍历的位置
int find(int root,int n)
{
if (n == 1)return 0;
if ((pos[pre[root]] == 0))
if (mark[in[pos[pre[root]] + 1]] == -1)//在左边界的判断
return root;
if ((pos[pre[root]] == n-1))
if (mark[in[pos[pre[root]] - 1]] == -1)//在右边界的判断
return root;
if (mark[in[pos[pre[root]] + 1]] == -1 && mark[in[pos[pre[root]] - 1]] ==-1)//中间的判断
return root;
if (pos[pre[root]] != 0)//有左子树
{
mark[pre[root]] = -1;
int left = find(root + 1, pos[pre[root]] + 1); return left;
}
if (pos[pre[root]] != n - 1)//有右子树
{
mark[pre[root]] = -1;
int right = find(root + pos[pre[root]] + 1, n - pos[pre[root]]);
return right;
}
}
int main()
{
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]);
pos[in[i]] = i;
}
printf("%d", pre[find(0,n)]);
}
法二:
#include<iostream>
#include<vector>
using namespace std;
bool flag = false;
vector<int>in, pre;
void post(int root,int inl, int inr)
{
if (inl>inr||flag == true)return;
int i = inl;
while(in[i] != pre[root])
i++;
post(root + 1, inl, i-1);
post(root+i+1-inl,i+1,inr);
if(flag==false)
printf("%d", in[i]);
flag = true;
}
int main()
{
int n;
scanf("%d", &n);
in.resize(n);
pre.resize(n);
for (int i = 0; i < n; i++)
scanf("%d", &pre[i]);
for (int i = 0; i < n; i++)
scanf("%d", &in[i]);
post(0,0,n);
}