1138 postorder traversal (25 分)

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

题意: 给定前序中序,建立二叉树,输出后序二叉树的第一个。

代码


using namespace std;

int n;
struct
{
int val;
struct *left,*right;
Node(int val): val(val),left(NULL),right(NULL) {} ;
};
int A[50050],B[50050];
vector<int>ans;
Node* build(int pl,int pr,int il,int ir)
{
if(pl>pr)
return NULL;
Node *root=new Node(A[pl]);
int idex;
for(int i=il;i<=ir;i++)
{
if(A[pl]==B[i])
{
idex=i;
break;
}
}
root->left = build(pl+1,idex-il+pl,il,idex-1);
root->right = build(idex-il+pl+1,pr,idex+1,ir);
return root;
}
void postorder(Node *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
ans.push_back(root->val);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
ans.clear();
Node *root=NULL;
for(int i=0;i<n;i++)
scanf("%d",&A[i]);
for(int i=0;i<n;i++)
scanf("%d",&B[i]);
root = build(0,n-1,0,n-1);
postorder(root);
printf("%dn",ans[0]);
}
return 0;
}