代码如下:
package algorithm;
import java.util.LinkedList;
public class TwoForkTree {
//private int[] array = {1,2,3,4,5,6,7,8,9};
//private char[] array = {'a','b','c','d','e','f','g','h','i'};
private Object[] array = {'a','b','c','d','e','f','g','h','i'};
LinkedList linkedList = null;
private class Node {
Object data;
Node leftChild = null;
Node rightChild = null;
Node(Object data) {
this.data = data;
}
}
public void CreateBinTree() {
int parentIndex ;
linkedList = new LinkedList();
for(int i=0;i
linkedList.add(new Node(array[i]));
}
for(parentIndex = 0;parentIndex < array.length/2-1;parentIndex++) {
linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);
linkedList.get(parentIndex).rightChild = linkedList.get(parentIndex*2+2);
}
if(array.length % 2 == 0) {
linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);
} else {
linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);
linkedList.get(parentIndex).rightChild = linkedList.get(parentIndex*2+2);
}
}
//preOrderTraverse 先序遍历
public void preOrderTraverse(Node root) {
if(root==null)
return;
System.out.print(root.data + " ");
preOrderTraverse(root.leftChild);
preOrderTraverse(root.rightChild);
}
//preOrderTraverse 中序遍历
public void inOrderTraverse(Node root) {
if(root==null)
return;
inOrderTraverse(root.leftChild);
System.out.print(root.data + " ");
inOrderTraverse(root.rightChild);
}
//preOrderTraverse 后序遍历
public void postOrderTraverse(Node root) {
if(root==null)
return;
postOrderTraverse(root.leftChild);
postOrderTraverse(root.rightChild);
System.out.print(root.data + " ");
}
public static void main(String[] args) {
TwoForkTree twoForkTree = new TwoForkTree();
twoForkTree.CreateBinTree();
System.out.println("-----------------先序遍历---------------------");
twoForkTree.preOrderTraverse(twoForkTree.linkedList.get(0));
System.out.println("\n-----------------中序遍历---------------------");
twoForkTree.inOrderTraverse(twoForkTree.linkedList.get(0));
System.out.println("\n-----------------后序遍历---------------------");
twoForkTree.postOrderTraverse(twoForkTree.linkedList.get(0));
}
}