题目
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 (<=50000), 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
题目分析
已知前序和中序,求后序第一个节点值
解题思路
- postFirst函数本质是建树过程,找到后序遍历的第一个节点后退出以节省时间(后序第一个节点为递归过程中第一个左子节点和右子节点都为NULL的节点)
易错点
该题节点数最多为50000个,若在找到后没有退出(即:完成建树过程)会超时
Code
Code 01
#include <iostream>
#include <vector>
const int maxn = 50000;
struct node {
int data;
node * left;
node * right;
};
int n,pre[maxn],in[maxn];
bool flag;
void postFirst(int inL,int inR, int preL,int preR) {
if(inL>inR||flag) return;
int k=inL;
while(k<inR&&in[k]!=pre[preL])k++;
postFirst(inL, k-1, preL+1, preL+(k-inL));
postFirst(k+1, inR, preL+(k-inL)+1, preR);
if(flag==false) {
printf("%d", pre[preL]);
flag=true;
}
}
int main(int argc,char * argv[]) {
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]);
postFirst(0,n-1,0,n-1);
}