PAT甲級A1138 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

題意:給出二叉樹的先序和中序序列,讓你輸出這棵二叉樹後序的第一個數。

思路:如果先建樹再後序訪問輸出的話,會超時。考慮到使用先序和中序序列遞歸建樹時,每次碰到葉節點時都是prel==prer,其中prel是先序序列的左邊界,prer是先序序列的右邊界,即每次到葉結點時,序列中都只有一個數,而後序下的第一個數就是第一個葉結點,因此當第一次碰到prel==prer時輸出這個結點數據,即可。

參考代碼:

#include<cstdio>
using namespace std;
int pre[50010],in[50010],n,idx=0;	
void create(int prel,int prer,int inl,int inr){
	if(prel>prer) return ;
	if(prel==prer&&!idx){
		printf("%d\n",pre[prel]);
		idx=1;				//idx標記是否已經輸出第一個葉結點,輸出後令idx=1
	}
	int k=inl;
	while(k<=inr&&in[k]!=pre[prel]) k++;
	int numL=k-inl;
	if(idx) return;				//已輸出提前退出
	create(prel+1,prel+numL,inl,k-1);
	if(idx) return;				//已輸出提前退出
	create(prel+numL+1,prer,k+1,inr);
}
int main()
{
	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]);
	create(0,n-1,0,n-1);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章