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());
}
}