二叉树顺序存储就是根据数组来存放二叉树,通过如果这个节点下标为n,其左子节点为2n+1,右节点为2n+2来判断。
在二叉树顺序存储中只考虑完全二叉树。
package tree;
public class arrdinarytree {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
arrbinarytree tree=new arrbinarytree(arr);
System.out.println("前序存储");
tree.preorder();
System.out.println("中序存储");
tree.midorder(0);
System.out.println("后序存储");
tree.postorder(0);
}
}
class arrbinarytree
{
private int[] array;
public arrbinarytree(int [] arr)
{
this.array=arr;
}
public void preorder()
{
preorder(0);
}
/**
*
* @param index数组的下标
*/
public void preorder(int index)
{
if(array.length==0||array==null)
{
System.out.println("数组为空");
}
System.out.println(array[index]);
if(2*index+1<array.length)
{
preorder(2*index+1);
}
if(2*index+2<array.length)
{
preorder(2*index+2);
}
}
public void midorder(int index)
{
if(array.length==0||array==null)
{
System.out.println("数组为空");
}
if(2*index+1<array.length)
{
midorder(2*index+1);
}
System.out.println(array[index]);
if(2*index+2<array.length)
{
midorder(2*index+2);
}
}
public void postorder(int index)
{
if(array.length==0||array==null)
{
System.out.println("数组为空");
}
if(2*index+1<array.length)
{
postorder(2*index+1);
}
if(2*index+2<array.length)
{
postorder(2*index+2);
}
System.out.println(array[index]);
}
}