顺序储存二叉树
顺序储存二叉树的遍历
public class ArrBinaryTreeDemo {
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6,7};
ArrBinaryTree abt=new ArrBinaryTree(arr);
abt.preOrder();
System.out.println("-----------------------------------");
abt.infixOrder();
System.out.println("-----------------------------------");
abt.postOrder();
}
}
class ArrBinaryTree{
private int[] arr;
public ArrBinaryTree(int[] arr) {
this.arr = arr;
}
public void preOrder(){
this.preOrder(0);
}
//前序遍历
public void preOrder(int index){
if(arr==null||arr.length==0)
{
System.out.println("数组为空");
return;
}
System.out.println(arr[index]);
if((index*2+1)<arr.length)
preOrder(2*index+1);
if((index*2+2)<arr.length)
preOrder(2*index+2);
}
public void infixOrder(){
this.infixOrder(0);
}
//中序遍历
public void infixOrder(int index){
if(arr==null||arr.length==0)
{
System.out.println("数组为空");
return;
}
if((index*2+1)<arr.length)
infixOrder(2*index+1);
System.out.println(arr[index]);
if((index*2+2)<arr.length)
infixOrder(2*index+2);
}
public void postOrder(){
this.postOrder(0);
}
//后序遍历
public void postOrder(int index){
if(arr==null||arr.length==0)
{
System.out.println("数组为空");
return;
}
if((index*2+1)<arr.length)
postOrder(2*index+1);
if((index*2+2)<arr.length)
postOrder(2*index+2);
System.out.println(arr[index]);
}
}