您的位置:首页 > 其它

【PAT】1020. Tree Traversals (25)

2014-11-05 11:09 253 查看
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}

public class Main {

public static void preorderPrint(TreeNode root) {
if (root != null) {
System.out.print(" " + root.val);
if (root.left != null)
preorderPrint(root.left);
if (root.right != null)
preorderPrint(root.right);
}
}

public static ArrayList<Integer> levelPrint(TreeNode root) {
ArrayList<Integer> resultList = new ArrayList<Integer>();
LinkedList<TreeNode> linkedList = new LinkedList<TreeNode>();
if (root == null)
return null;
linkedList.add(root);
int preNum = 1, nextNum = 0;
while (linkedList.size() > 0) {
TreeNode firstNode = linkedList.getFirst();
linkedList.removeFirst();
resultList.add(firstNode.val);
preNum--;
if (firstNode.left != null) {
linkedList.add(firstNode.left);
nextNum++;
}
if (firstNode.right != null) {
linkedList.add(firstNode.right);
nextNum++;
}
if (preNum == 0) {
preNum = nextNum;
nextNum = 0;
}
}
return resultList;
}

public static TreeNode createTree(int[] a, int[] b, int af, int al, int bf,
int bl) {
int i,nextlen;
if (al < af)
return null;
TreeNode root = new TreeNode(a[al]);
for (i = bf; i <= bl; i++) {
if (a[al] == b[i])
break;
}
nextlen=i-bf;
/*		System.out.println("af:"+af+" al:"+al+" bf:"+bf+" bl:"+bl);
System.out.println("i="+i);*/
root.left = createTree(a, b, af, af + nextlen - 1, bf, bf + nextlen - 1);
root.right = createTree(a, b, af + nextlen, al - 1, bf + nextlen + 1, bl);
return root;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] a = new int
;// postorder
int[] b = new int
;// inorder
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = input.nextInt();
}
TreeNode rootNode = null;
rootNode = createTree(a, b, 0, n - 1, 0, n - 1);
ArrayList<Integer> ansList=levelPrint(rootNode);
for(int i=0;i<ansList.size();i++){
if(i!=ansList.size()-1)System.out.print(ansList.get(i)+" ");
else System.out.println(ansList.get(i));
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: