1138 Postorder Traversal
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<vector>
using namespace std;
vector<int>preOrder, inOrder;
int flag = 1;
void solve(int root, int inl, int inr) {
if (inl >= inr)
return;
int i = inl;
while (i < inr&&inOrder[i] != preOrder[root]) { i++; }
int l = i - inl;
solve(root + 1, i - l, i);
solve(root + 1 + l, i + 1, inr);
if (flag) {
cout << preOrder[root];
flag = 0;
}
}
int main(){
int n;
scanf_s("%d", &n);
preOrder.resize(n);
inOrder.resize(n);
for(int i = 0; i<n; i++) scanf_s("%d",&preOrder[i]);
for(int i = 0; i<n; i++) scanf_s("%d", &inOrder[i]);
solve(0, 0, n);
return 0;
}
本文介绍了一种算法,用于将二叉树的前序和中序遍历序列转换为后序遍历序列,特别关注于输出后序遍历的第一个数字。通过递归方法解析输入序列,适用于所有节点为唯一正整数的二叉树。
470

被折叠的 条评论
为什么被折叠?



