【PAT】1020. Tree Traversals (25)

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[n];// postorder
		int[] b = new int[n];// 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));
		}

	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值