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<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left,*right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* build(int pl, int pr, int il, int ir, vector<int>& preorder, vector<int>& inorder)
{
if (pl > pr || il > ir)
return NULL;
TreeNode* root = new TreeNode(preorder[pl]);
int rootin;
for (rootin = il; inorder[rootin] != root->val; rootin++);
root->left = build(pl + 1, pl + rootin - il, il, rootin - 1, preorder, inorder);
root->right = build(pl + 1 + rootin - il, pr, rootin + 1, ir, preorder, inorder);
return root;
}
vector<int>re;
void dfs(TreeNode* root)
{
if (!root || re.size()) return;
dfs(root->left);
dfs(root->right);
re.push_back(root->val);
}
int main()
{
int n, a;
cin >> n;
vector<int>preorder(n), inorder(n);
for (int i = 0; i < n; i++)
scanf("%d", &preorder[i]);
for (int i = 0; i < n; i++)
scanf("%d", &inorder[i]);
TreeNode* root = build(0, n - 1, 0, n - 1, preorder, inorder);
dfs(root);
cout << re.front();
return 0;
}