//节点类
class NodeTree{
public static NodeTree first;
public String Value;
public NodeTree leftChild;
public NodeTree rightChild;
public NodeTree(){
}
}
public class tree {
/*
前序(根-左-右):ABCDEF
中序(左-根-右):CBDAEF
后序(左-右-根):CDBFEA
*/
public static void main(String []args){
String a="ABCDEF";
String b="CBDAEF";
buildTree(a,b,null);
new tree().haha(NodeTree.first);
}
//后序遍历二叉树
public void haha(NodeTree n){
if(n.leftChild!=null){
haha(n.leftChild);
}
if(n.rightChild!=null){
haha(n.rightChild);
}
System.out.print(n.Value);
}
//递归建树
public static NodeTree buildTree(String frontChar,String behindChar,NodeTree father){
NodeTree nodeTree=new NodeTree();
if(father==null){
//创立根节点并标记
NodeTree.first=nodeTree;
}
nodeTree.Value=String.valueOf(frontChar.charAt(0));
//判断是否有子节点
if(frontChar.length()==1||frontChar==""){
return nodeTree ;
}
int head=0;
int mid=behindChar.indexOf(frontChar.charAt(head));
//划分左子树
String a=frontChar.substring(1, mid+1);
String b=behindChar.substring(0,mid);
//左节点的值 判断是否有左子树
if(a.length()>=1&&b.length()>=1)
nodeTree.leftChild=buildTree(a,b,nodeTree);
//划分右子树
String c=frontChar.substring(mid+1, frontChar.length());
String d=behindChar.substring(mid+1,behindChar.length());
//右节点的值 判断是否有右子树
if(c.length()>=1&&d.length()>=1)
nodeTree.rightChild=buildTree(c,d,nodeTree);
//返回本层节点 作为上层递归的子节点
return nodeTree;
}
}