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
有意思的一点:
跑这个程序死活跑不出来一直段错误,但明明可以跑出答案。参考了柳神的代码,发现有个地方逻辑是相似的,
但不同的写法造成天差地别的结果?还未弄懂原因~~
#include <iostream>
#include <map>
#include <vector>
using namespace std;
map<int, int> pos;
int N;
vector<int> inorder;
vector<int> preorder;
bool flag = false;
void postL(int inl, int inr, int preRoot){
if (inl > inr || flag == true) return;
int inRoot = pos[preRoot];
postL(inl, inRoot-1, preRoot+1);
postL(inRoot+1, inr, preRoot+1+(inRoot - inl));
if (flag == false)
{
printf("%d", inorder[inRoot]);
flag = true;
}
}
int main(){
scanf("%d", &N);
inorder.resize(N+1), preorder.resize(N+1);
for (int i = 1; i <= N; i++) scanf("%d", &preorder[i]);
for (int i = 1; i <= N; i++){
scanf("%d", &inorder[i]);
pos[inorder[i]] = i;
}
postL(1,N,1);
return 0;
}
#include <iostream>
#include <map>
#include <vector>
using namespace std;
map<int, int> pos;
int N;
vector<int> inorder;
vector<int> preorder;
bool flag = false;
void postL(int inl, int inr, int preRoot){
if (inl > inr || flag == true) return;
int inRoot = inl;
while(inorder[inRoot] != preorder[preRoot])inRoot++;
postL(inl, inRoot-1, preRoot+1);
postL(inRoot+1, inr, preRoot+1+(inRoot - inl));
if (flag == false)
{
printf("%d", inorder[inRoot]);
flag = true;
}
}
int main(){
scanf("%d", &N);
inorder.resize(N+1), preorder.resize(N+1);
for (int i = 1; i <= N; i++) scanf("%d", &preorder[i]);
for (int i = 1; i <= N; i++){
scanf("%d", &inorder[i]);
pos[inorder[i]] = i;
}
postL(1,N,1);
return 0;
}