先创建二叉树的节点类
public class Node{
Node leftChild;
Node rightChild;
int data;
public Node(Node leftChild, Node rightChild, int data){
this.leftChild = leftChild;
this.rightChild = rightChild;
this.data = data;
} //这个是构造中间节点
public Node(int data){
this.data = data;
this.leftChild = null;
this.rightChild = null;
} //左右子树为空的叶子节点
}
创建二叉树的遍历类
public class BinaryTree {
public int[] array = {1,2,3,4,5,6,7,8,9};
public static List<Node> nodeList = null; //创建一个空的树
public void createBinaryTree(){
nodeList = new LinkedList<Node>();//创建一个对象
for(int nodeIndex = 0; nodeIndex < array.length; nodeIndex++){
Node beAdd = new Node(array[nodeIndex]);//将数组里的值转化为树节点Node的形式
//转化为Node是用Node这个class的构造方法,填入一个数值,然后左右子树暂时默认为null
System.out.print("添加的是"+array[nodeIndex]);
nodeList.add(beAdd); //将树节点加入该树中
}
/**
父节点个数和总节点数的数学关系为 节点数除于2取整数就是父节点的个数
因为最后一个父节点可能没有子树,所以最后一个节点要另外讨论
需要注意的是,这个数学关系仅对完全二叉树有效
父节点和左子树的关系是2*n+1
父节点和右子树的关系是2*n+2
*/
//对树进行赋值
for(int parentIndex=0;parentIndex < array.length/2-1 ;parentIndex++){
nodeList.get(parentIndex).leftChild = nodeList.get(parentIndex*2+1);
nodeList.get(parentIndex).rightChild = nodeList.get(parentIndex*2+2);
}
//对最后一个父节点的左子树进行赋值
int lastParentIndex = array.length/2-1;
nodeList.get(lastParentIndex).leftChild = nodeList.get(lastParentIndex*2+1);
if(array.length%2==1){ //存在右子树
nodeList.get(lastParentIndex).rightChild = nodeList.get(lastParentIndex*2+2);
}
}
public static void preOrederTraverse(Node node){ //前序遍历
if(node == null) return;
System.out.print(node.data + " ");
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
}
public static void inOrederTraverse(Node node){ //中序遍历
if(node == null) return;
preOrderTraverse(node.leftChild);
System.out.print(node.data + " ");
preOrderTraverse(node.rightChild);
}
public static void postOrederTraverse(Node node){ //后序遍历
if(node == null) return;
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
System.out.print(node.data + " ");
}
}