//借鉴达哥的程序
2035: Leaf Nodes
--------------------------------------------------------------------------------
Status In/Out TIME Limit MEMORY Limit Submit Times Solved Users JUDGE TYPE
stdin/stdout 1s 10240K 224 104 Standard
Kate is learning about binary tree. She think she know everything you know about binary trees. Wait, you don't know binary tree? Find a book about data structures, and it will just take you about three minutes. Now here is a binary tree:
3
/ /
/ /
2 4
/ / /
/ / /
0 1 6
/
/
5Kate think she also know something that you may not notice. First, for some type of binary trees, only the leaf nodes have the meaning (leaf node is the node which has no sub trees, for the tree above, the leaf nodes are 0 1 5), an example is the Huffman Tree. Second, she guess that if you know the preorder traversal and the postorder traversal of a binary tree, you can ensure the leaf node of the tree, and their order.
For the tree above, the preorder travesal is 3 2 0 1 4 6 5 and the postorder travesal is 0 1 2 5 6 4 3, the leaf nodes in order(from left to right) are 0 1 5.
But now the problem is she just guess it, if you can find a way to print a tree's leaf nodes in order using its preorder traversal and postorder traversal, you can say "she is right!"
Input Specification
The input file will contain one or more test cases. In each test case there is a integer n (0<=n <= 10000), indicating the tree have n nodes, then followed two lists of integers, either contains n integers in the range of 0 and n-1 (both included), the first list is the preorder traversal, and the other is the postorder traversal.
Input is terminated by an interger -1;
Output Specification
For each test case, print the tree's leaf nodes in order, each in a line.
Sample Input
7
3 2 0 1 4 6 5
0 1 2 5 6 4 3
-1Sample Output
0
1
5思路是这样的,因为先根遍历是中左右,后根遍历是左右中,所以左都在右前面。在后根遍历的序列里,从前往后,比如,由于后根遍历第一个肯定是叶子,那么在先根遍历里找那个结点,它前面的就是中,全部标记为-1,所以它们肯定不是叶子。
算法里面主要是COUNT来记录序号,用-1标记,领会领会!
#include<iostream>
int a[10000],b[10000];
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int n,i,j,k,count;
while((scanf("%d",&n),n)>0)
{
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++) scanf("%d",&b[i]);
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(b[i]==a[j])
{
printf("%d/n",b[i]);
for(k=count;k<j;k++)
a[k]=-1;
count=j+1;
}
}
return 0;
}