package demoFive;
/*
*@author:张文波
*@time2020年4月18日上午10:22:33
*/
//已知二叉树前序和中序序列,求二叉树
public class BuildTree
{
public static String xian="ABC";
public static String zhong="BAC";
public static int pos=0;
public static void main(String[] args)
{
node n=createTree(zhong);
System.out.println("创建成功");
NodePrint(n);
}
// 遍历链表
public static void NodePrint(node n)
{
while (n == null)
{
return;
}
System.out.println(n.data);
NodePrint(n.getLeft());
NodePrint(n.getRight());
}
//创建二叉树
public static node createTree(String zhong) {
if(zhong.length()<=0||pos>xian.length()) {
pos--;
return null;
}
node n=new node();
n.setData(xian.charAt(pos));
int site=0;
//匹配字符
for(int i=0;i<zhong.length();i++) {
String temp=zhong.substring(i,i+1);
if(temp.equals(String.valueOf(xian.charAt(pos)))) {
site=i;
break;
};
}
pos++;
n.setLeft(createTree(zhong.substring(0,site)));
pos++;
n.setRight(createTree(zhong.substring(site+1,zhong.length())));
return n;
}
}
class node{
char data;
node left;
node right;
public char getData()
{
return data;
}
public void setData(char data)
{
this.data = data;
}
public node getLeft()
{
return left;
}
public void setLeft(node left)
{
this.left = left;
}
public node getRight()
{
return right;
}
public void setRight(node right)
{
this.right = right;
}
}