1. 运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/36ac9283b63d6d781223f2ea97ef7f07.png)
2. 节点类
package Class.Binarytree;
public class BinaryNode {
private String data;
BinaryNode left, right;
public BinaryNode(String data) {
this.data = data;
}
public BinaryNode(String data, BinaryNode left, BinaryNode right) {
this.data = data;
this.left = left;
this.right = right;
}
public String toString() {
return data;
}
}
3. 二叉树类
package Class.Binarytree;
public class BinaryTree {
private BinaryNode root;
public BinaryTree(String preStr, String inStr) {
root = this.preBuild(preStr, inStr);
}
public BinaryNode preBuild(String preStr, String inStr) {
String fatherAlpha;
BinaryNode father;
BinaryNode leftSon;
BinaryNode rightSon;
fatherAlpha = preStr.substring(0, 1);
father = new BinaryNode(fatherAlpha);
int inIndex = inStr.indexOf(fatherAlpha);
int leftLength = 0;
if (inIndex != 0) {
String inLeft = inStr.substring(0, inIndex);
leftLength = inLeft.length();
String preLeft = preStr.substring(1, leftLength + 1);
father.left = preBuild(preLeft, inLeft);
}
if (inIndex + 1 != inStr.length()) {
String inRight = inStr.substring(inIndex + 1);
String preRight = preStr.substring(leftLength + 1);
father.right = preBuild(preRight, inRight);
}
return father;
}
public void postBuild(String inStr, String postStr) {
}
public void preOrder() {
preOrder(root);
System.out.println("");
}
public void preOrder(BinaryNode node) {
if (node != null) {
System.out.print(node.toString());
preOrder(node.left);
preOrder(node.right);
}
}
public void inOrder() {
inOrder(root);
System.out.println("");
}
public void inOrder(BinaryNode node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.toString());
inOrder(node.right);
}
}
public void postOrder() {
postOrder(root);
System.out.println("");
}
public void postOrder(BinaryNode node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
System.out.print(node.toString());
}
}
}
4. 主类
package Class.Binarytree;
public class main {
public static void main(String[] args) {
BinaryTree tree1 = new BinaryTree("DFIG", "IFDG");
tree1.preOrder();
tree1.inOrder();
tree1.postOrder();
BinaryTree tree2 = new BinaryTree("ABCDEF", "CBAEDF");
tree2.preOrder();
tree2.inOrder();
tree2.postOrder();
BinaryTree tree3 = new BinaryTree("ABCIDEHFJG","BICAHEJFGD");
tree3.preOrder();
tree3.inOrder();
tree3.postOrder();
}
}