一、概念
二叉树的顺序存储就是用一组连续的存储单元存放二叉树中的结点元素,一般按照二叉树结点自上向下、自左向右的顺序存储。
二、实现思路及特点
完全二叉树示例图:
其中数字代表其在数组的索引值,这里我们构造一个完全二叉树,节点值分别放置A B C D E F G这七个数据,其节点与数组的索引值对应关系如下图所示(数字代表其在数组的索引值)
完全二叉树抽象成一维数组:其节点和索引的对应关系
1、顺序二叉树通常只考虑完全二叉树;
2、第n+1个节点其左子节点在数组中的索引值为2n+1;(其中n代表数组的索引值)
3、第n+1个节点其右子节点在数组中的索引值为2n+2;(其中n代表数组的索引值)
三、代码实现
1、前序遍历:
/**
* 前序遍历
* 1、顺序二叉树通常只考虑完全二叉树;
* 2、第n+1个节点其左子节点在数组中的索引值为2n+1;(其中n代表数组的索引值)
* 3、第n+1个节点其右子节点在数组中的索引值为2n+2;(其中n代表数组的索引值)
* @param r_index:父节点对应的数组索引值
*/
private void preShow(int r_index){
System.out.print(arr[r_index]+" ");
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
preShow(left);
}
if(right<arr.length){//右递归
preShow(right);
}
}
2、中序遍历:
/**
* 中序遍历
* @param r_index:父节点对应的数组索引值
*/
private void infixShow(int r_index){
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
infixShow(left);
}
System.out.print(arr[r_index]+" ");
if(right<arr.length){//右递归
infixShow(right);
}
}
3、后序遍历:
/**
* 后序遍历
* @param r_index:父节点对应的数组索引值
*/
private void aftShow(int r_index){
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
aftShow(left);
}
if(right<arr.length){//右递归
aftShow(right);
}
System.out.print(arr[r_index]+" ");
}
4、完整例子测试代码:
import java.util.Arrays;
public class ArrayBinaryTree {
public static void main(String[] args) {
char []arr={'A','B','C','D','E','F','G'};
System.out.println("数组:"+ Arrays.toString(arr));
array_binaryTree array_binaryTree = new array_binaryTree(arr);
//前序遍历:A B D E C F G
System.out.print("前序遍历:");
array_binaryTree.preShow();//前序遍历
//中序遍历:D B E A F C G
System.out.print("中序遍历:");
array_binaryTree.infixShow();//中序遍历
//后序遍历:D E B F G C A
System.out.print("后序遍历:");
array_binaryTree.aftShow();//中序遍历
}
}
class array_binaryTree{
private char[]arr;// 存储数据节点
public array_binaryTree(char[] arr) {
this.arr = arr;
}
//前序遍历
public void preShow(){
this.preShow(0);
System.out.println();
}
//中序遍历
public void infixShow(){
this.infixShow(0);
System.out.println();
}
//后序遍历
public void aftShow(){
this.aftShow(0);
System.out.println();
}
/**
* 前序遍历
* 1、顺序二叉树通常只考虑完全二叉树;
* 2、第n+1个节点其左子节点在数组中的索引值为2n+1;(其中n代表数组的索引值)
* 3、第n+1个节点其右子节点在数组中的索引值为2n+2;(其中n代表数组的索引值)
* @param r_index:父节点对应的数组索引值
*/
private void preShow(int r_index){
System.out.print(arr[r_index]+" ");
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
preShow(left);
}
if(right<arr.length){//右递归
preShow(right);
}
}
/**
* 中序遍历
* @param r_index:父节点对应的数组索引值
*/
private void infixShow(int r_index){
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
infixShow(left);
}
System.out.print(arr[r_index]+" ");
if(right<arr.length){//右递归
infixShow(right);
}
}
/**
* 后序遍历
* @param r_index:父节点对应的数组索引值
*/
private void aftShow(int r_index){
int left=2*r_index+1;//左子节点索引
int right=2*r_index+2;//右字节点索引
if(left<arr.length){//左递归
aftShow(left);
}
if(right<arr.length){//右递归
aftShow(right);
}
System.out.print(arr[r_index]+" ");
}
}
5、测试结果: