已知一棵树的先序遍历和中序遍历,获取其后序遍历

public class Test {
	
	public class Tree{
		public String data;
		public Tree left;
		public Tree right;
	}
	
	public Tree buildTree(String a,String b)
	{
		Tree root = new Tree();
		int apos = 0;
		int bpos = 0;
		int len = b.length();
		buildTree(root,a,apos,b,bpos,len);
		return root;
	}
	
	private void buildTree(Tree root,String a,int apos,String b,int bpos,int len) {
		root.data = a.substring(apos, apos + 1);
		int pos = b.indexOf(root.data);
		if(pos > bpos){
			root.left = new Tree();
			buildTree(root.left, a, apos + 1, b, bpos,len - pos - 1);
		}
		if(pos > len) {
			if(pos - bpos < len - 1) {
				root.right = new Tree();
				buildTree(root.right, a, pos + 1, b, pos + 1, len - pos - 1);
			}
		}else {
			if(pos < len - 1) {
				root.right = new Tree();
				buildTree(root.right, a, apos + pos + 1, b, pos + 1, len - pos - 1);
			}
		}
	}
	
	public void travel(Tree root,StringBuilder result) {
		if(root != null) {
			travel(root.left, result);
			travel(root.right, result);
			result.append(root.data);
		}
	}
	
	public static void main(String[] args) {
		String str = "AFEGBCK,EFGABKC";
		String[]strs = str.split(",");
		Test t = new Test();
		Tree root = t.buildTree(strs[0], strs[1]);
		StringBuilder result = new StringBuilder();
		t.travel(root, result);
		System.out.println(result.toString());
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值