题目描述
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
求解思路
- 题意:给定结点个数n以及前序遍历序列和中序遍历序列,要求我们给出后序遍历序列的第一个元素值。
- 定义一个结构体,用于保存结点值,左子结点指针、右子节点指针。
- 假设前序遍历序列区间为[preL,preR],中序遍历序列区间为[inL,inR]。
- 如果preL>preR,那么返回空结点。
- 对于一棵树,根节点的值为前序遍历第一个结点的值,即pre[preL]。在中序遍历中找到一个位置pos使得in[pos]==pre[preL],然后划分左右子树,左子树为create(preL+1,preL+pos-inL,inL,pos-1),右子树为create(preL+pos+1-inL,preR,pos+1,inR)
代码实现(AC)
#include<cstdio>
struct Node{
int data;
Node *lchild;
Node *rchild;
};
int n,cnt=0;
int pre[50001],in[50001];
Node *create(int preL,int preR,int inL,int inR)
{
if(preL>preR) return NULL;
Node *root=new Node;
root->data=pre[preL];
int pos=inL;
for(;pos<=inR;pos++)
if(pre[preL]==in[pos]) break;
root->lchild=create(preL+1,preL+pos-inL,inL,pos-1);
root->rchild=create(preL+pos+1-inL,preR,pos+1,inR);
return root;
}
void postTraversal(Node *root)
{
if(root==NULL) return ;
postTraversal(root->lchild);
postTraversal(root->rchild);
if(cnt==0)
{
printf("%d",root->data);
cnt++;
}
}
void solve()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&pre[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
Node *root=create(0,n-1,0,n-1);
postTraversal(root);
}
int main()
{
solve();
return 0;
}