java中根遍历序列和后根遍历序列,建立二叉树

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

2.实现类

public class test {

 public static void main(String[] args) {

String postOrder = "DGEBHFCA";

String inOrder = "DBGEAFHC";

BiTree T = new BiTree(postOrder,inOrder,postOrder.length()-1,postOrder.length()-1,postOrder.length());

System.out.println("先根遍历为:");

BiTreeNode root = T.getRoot();      //取得树的根结点

T.preRootTraverse(root);

System.out.println();

 System.out.println("后根遍历");

T.postRootTraverse(root);

System.out.println();

System.out.println("中根遍历");

T.inRootTraverse(root);

 }
}

3.运行结果:

先根遍历为:
ABDEGCFH
后根遍历
DGEBHFCA
中根遍历
DBGEAFHC

你可能感兴趣的:(数据结构与算法)