1.递归建立二叉树
由中根遍历的数组和后根遍历的数组建立一棵二叉树,其中参数inOrder是整棵树的中根遍历,postOrder是整棵树的后根遍历,inIndex是 中根遍历从inOrder字符串中的inOrder的最后一个位置,postIndex是后根遍历从字符串postOrder 中的最后一个位置,count表示树结点的个数。
public BiTree( String postOrder, String inOrder, int postIndex,int inIndex,int count) {
if (count > 0) {// 中根和后根非空
char r = postOrder.charAt(postIndex);// 取后根字符串中的最后一个元素作为根结点
int i =0 ;
for (; i<count; i++) {
// 寻找根结点在中根遍历字符串中的索引
if (r == inOrder.charAt( inIndex-i)) {
break;
}
}
root = new BiTreeNode(r);// 建立树的根结点
root.rchild= new BiTree( postOrder,inOrder,postIndex-1,inIndex, i).root;// 建立树的右子树
root.lchild= new BiTree( postOrder, inOrder,postIndex-i-1,inIndex -i-1,count-i-1).root;// 建立树的左子树
}
}
2.实现类
public class test {
public static void main(String[] args) {
String postOrder = "DGEBHFCA";
String inOrder = "DBGEAFHC";
BiTree T = new BiTr