1020 Tree Traversals (25 分)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order 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 (≤30), the total number of nodes in the binary tree. The second line gives the postorder 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 level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题目大意:
给定后序遍历和中序遍历,求层序遍历。这个层序遍历用数组来存的话,数组大小可不是2*n+2,是2的n次方,所以用Arraylist存下他的下标和对应的值,最后按下标排序,输出非0值。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Comparator;
public class Main2 {
static int N;
static int []post;
static int [] inorder;
static ArrayList<Node> level = new ArrayList<>();
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
N = (int)in.nval;
post = new int[N];
inorder = new int[N];
for(int i =0;i<N;i++) {
in.nextToken();
post[i] = (int)in.nval;
}
for(int i=0;i<N;i++) {
in.nextToken();
inorder[i] = (int)in.nval;
}
int root = buildtree(0,N-1,N-1,0);
level.sort(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
// TODO Auto-generated method stub
return o1.index-o2.index;
}
});
int flag = 0;
for(Node num:level) {
if(flag==0&&num.data!=0) {
System.out.print(num.data);
flag=1;
}
else if(num.data!=0)
System.out.print(" "+num.data);
}
}
private static int buildtree(int inL, int inR, int postR, int index) {
// TODO Auto-generated method stub
if(inR<inL)
return 0;
int root = post[postR];
Node nd = new Node(index,root);
level.add(nd);
int pointer=-1;
for(int i=inL;i<=inR;i++) {
if(inorder[i]==root) {
pointer = i;
break;
}
}
buildtree(inL,pointer-1,postR-1-inR+pointer,index*2+1);
buildtree(pointer+1,inR,postR-1,index*2+2);
return 0;
}
}
class Node{
public Node(int index, int data) {
// TODO Auto-generated constructor stub
this.index = index;
this.data = data;
}
int index;
int data;
}