HDU1710—二叉树遍历
时间限制:1000ms,空间限制:32768K。
问题描述:二叉树是一组有限的顶点,或者为空或者由根r和两个不相交的子二叉树组成,称为左右子树。有三种最重要的遍历结点方式,即先序、中序和后序遍历。令T为有根r和子树T1、T2的二叉树,在T的先序遍历中,先访问根r,然后先序遍历T1,最后先序遍历T2。在T的中序遍历中,先中序遍历T1,然后访问根r,最后中序遍历T2。在T的后序遍历中,先后序中遍历T1,然后后序遍历T2,最后访问r。 现在给出一棵二叉树的先序遍历序列和中序遍历序列,试着找出它的后序遍历序列。 输入格式:输入包含几个测试用例。每个测试用例的第一行包含一个整数n(1≤n≤1000),即二叉树的结点数,后面跟着两行,分别表示先序遍历序列和中序遍历序列,你可以假设它们唯一构造一棵二叉树。 输出格式:对于每个测试用例,打印一行指定相应的后序遍历序列。
输入用例
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
输出用例
7 4 2 8 9 5 6 3 1
import java.util.*;
import java.util.Scanner;
class BTNode
{ int data;
BTNode lchild;
BTNode rchild;
public BTNode()
{
lchild=rchild=null;
}
public BTNode(int d)
{ data=d;
lchild=rchild=null;
}
}
public class Main
{ final static int MAXN=1005;
static int[] ans=new int[MAXN];
static int k;
public static BTNode CreateBT1(int[] pre,int[] in,int n)
{
return CreateBT11(pre,0,in,0,n);
}
private static BTNode CreateBT11(int[] pre,int i,int[] in,int j,int n)
{ BTNode t;
int d,p,k;
if (n<=0) return null;
d=pre[i];
t=new BTNode(d);
p=j;
while (p <j+n)
{ if (in[p]==d)
break;
p++;
}
k=p-j;
t.lchild=CreateBT11(pre,i+1,in,j,k);
t.rchild=CreateBT11(pre,i+k+1,in,p+1,n-k-1);
return t;
}
public static void PostOrder(BTNode root)
{ if (root!=null)
{
PostOrder(root.lchild);
PostOrder(root. rchild);
ans[k]=root.data; k++;
}
}
public static void main(String[] args)
{ Scanner fin = new Scanner(System.in);
int n;
int[] pre=new int[MAXN];
int[] in=new int[MAXN];
BTNode root;
while (fin.hasNext())
{ n=fin.nextInt();
for (int i=0;i <n;i++)
pre[i]=fin.nextInt();
for (int i=0;i <n;i++)
in[i]=fin.nextInt();
root=CreateBT1(pre,in,n);
k=0;
PostOrder(root);
for (int i=0; i <k-1;i++)
System.out.print(ans[i]+" ");
System.out.println(ans[k-1]);
}
}
}