顺序储存二叉树
基本说明:从数据存储来看,数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组
要求
1.以数组的方式来存放
2.遍历数组时,仍然可以用前序遍历,中序遍历,后序遍历的方式完成结点的遍历
特点
1.顺序二叉树通常只考虑完全二叉树
2.n表示二叉树中元素的下标,从0开始编号,n+1表示二叉树中第几个元素
3.下标为n的元素的左子节点对应的数组下标为2 * n + 1
4.下标为n的元素的右子节点对应的数组下标为2 * n + 2
5.下标为n的元素的父节点对应的数组下标为(n - 1) / 2
代码实现
public class ArrayBinaryTree {
private int[] arr;// 存储数据结点的数组
public ArrayBinaryTree(int[] arr) {
this.arr = arr;
}
//重载preList,因为固定从根节点开始遍历
public void preList() {
this.preList(0);
}
public void preList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
System.out.println(arr[index]);//输出当前元素
if ((index * 2 + 1) < arr.length) {//向左递归遍历
preList(2 * index + 1);
}
if ((index * 2 + 2) < arr.length) {//向右递归遍历
preList(2 * index + 2);
}
}
//重载infixList,因为固定从根节点开始遍历
public void infixList() {
this.infixList(0);
}
public void infixList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
if ((index * 2 + 1) < arr.length) {//向左递归遍历
infixList(2 * index + 1);
}
System.out.println(arr[index]);//输出当前元素
if ((index * 2 + 2) < arr.length) {//向右递归遍历
infixList(2 * index + 2);
}
}
//重载postList,因为固定从根节点开始遍历
public void postList() {
this.postList(0);
}
public void postList(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空");
}
if ((index * 2 + 1) < arr.length) {//向左递归遍历
postList(2 * index + 1);
}
if ((index * 2 + 2) < arr.length) {//向右递归遍历
postList(2 * index + 2);
}
System.out.println(arr[index]);//输出当前元素
}
}

浙公网安备 33010602011771号