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
solution:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef struct node *tree;
const int maxn=5e4+5;
int pre[maxn],in[maxn];
bool firstnode=false;
int ans;
struct node
{
int val;
tree left,right;
};
void preorder(tree root)
{
if(root==NULL)return;
preorder(root->left);
cout<<root->val<<' ';
preorder(root->right);
}
void postorder(tree root)
{
if(root==NULL)return;
postorder(root->left);
postorder(root->right);
if(!firstnode)
{
ans=root->val;
firstnode=true;
}
else return;
}
tree build(int in[],int pre[],int n)
{
tree t;
if(!n)return NULL;
t=new node;
t->val=pre[0];
t->left=t->right=NULL;
int i;
for(i=0;i<n;i++)
{
if(pre[0]==in[i])break;
}
t->left=build(in,pre+1,i);
t->right=build(in+1+i,pre+i+1,n-i-1);
return t;
}
int main()
{
int n;cin>>n;
for(int i=0;i<n;i++)cin>>pre[i];
for(int i=0;i<n;i++)cin>>in[i];
tree root=build(in,pre,n);
postorder(root);
cout<<ans;
//preorder(root);
}
716

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



