通过前序和中序构造二叉树,并输出后序

import java.util.Scanner;

public class Main {
	static String a[];//前
	static String b[];//中
	public static void main(String[] args)  {
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		sc.nextLine();
		while(n-->0){
		a=sc.nextLine().split(" ");
		b=sc.nextLine().split(" ");
		
		Node root= f(0,a.length-1,0,b.length-1);
		g(root);
		System.out.println();
		}
	}
	private static void g(Node root) {//后序
		if(root.left!=null)
			g(root.left);
		if(root.right!=null)
			g(root.right);
		System.out.print(root.num+" ");
	}
	private static Node f(int i, int j,int q,int w) {
		if(i==j) return new Node(a[i]);
		if(i>j) return null;
		Node temp = new Node(a[i]);
		int k=q;
		for (; k <w; k++) {
			if(a[i].equals(b[k]))
				break;
		}
			temp.left=f(i+1,k+i-q,q,k-1);
			temp.right=f(j+k-w+1,j,k+1,w);
		return temp;
	}

	
}

class Node{
	Node left;
	Node right;
	String num;
	public Node(String num) {
		super();
		this.num = num;
	}
	
}





测试二叉树:
前 9 10 12
中 10 12 9
后 12 10 9


前 3 6 7 11
中 6 3 11 7
后 6 11 7 3 




前 4 8 9 10 12
中 8 4 10 12 9
后 8 12 10 9 4


前 2 4 8 9 10 12 5
中 8 4 10 12 9 2 5
后 8 12 10 9 4 5 2


前 1 2 4 8 9 10 12 5 3
中 8 4 10 12 9 2 5 1 3
后 8 12 10 9 4 5 2 3 1


前 1 2 4 8 9 10 12 5 3 6 7 11
中 8 4 10 12 9 2 5 1 3 6 7 11
后 8 12 10 9 4 5 2 11 7 6 3 1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值