首先创建二叉树类
/**
*
* @author OucJeffrey
* qq:1020724110
* weibo:ouc大飞
*/
public class BinaryTree {
int data;//根节点数据
BinaryTree left;//左子树
BinaryTree right;//右子树
public BinaryTree(int data){//构造方法,实例化二叉树类
this.data=data;
left=null;
right=null;
}
public void insert(BinaryTree root,int data){//向二叉树中插入子节点
if (data>root.data) {//二叉树的右节点都比根大
if (root.right==null) {
root.right=new BinaryTree(data);
}else {
this.insert(root.right, data);
}
}else {//二叉树的左节点都比根小
if (root.left==null) {
root.left=new BinaryTree(data);
}else {
this.insert(root.left, data);
}
}
}
}
接着就是二叉树的前中后遍历了
/**
* @author OucJeffrey
* qq:1020724110
* weibo:ouc大飞
*/
public class BinaryTreeOrder {
public static void main(String[] args) {
int[] array={12,11,4,7,34,23,56,43,22,11,55};
BinaryTree root=new BinaryTree(array[0]);
for(int i=1;i<array.length-1;i++){
root.insert(root, array[i]);
}
System.out.println("先序遍历");
preOrder(root);
System.out.println();
System.out.println("中序遍历");
inOrder(root);
System.out.println();
System.out.println("后序遍历");
postOrder(root);
}
public static void preOrder(BinaryTree root){//先序遍历
if (root!=null) {
System.out.print(root.data+"--");
preOrder(root.left);
preOrder(root.right);
}
}
public static void inOrder(BinaryTree root){//中序遍历
if(root!=null){
inOrder(root.left);
System.out.print(root.data+"--");
inOrder(root.right);
}
}
public static void postOrder(BinaryTree root){//后续遍历
if (root!=null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+"--");
}
}
}
遍历结果
先序遍历
12--11--4--7--11--34--23--22--56--43--
中序遍历
4--7--11--11--12--22--23--34--43--56--
后序遍历
11--7--4--11--22--23--43--56--34--12--