二叉树的顺序存储,指的是使用顺序表(数组)存储二叉树。需要注意的是,顺序存储只适用于完全二叉树。换句话说,只有完全二叉树才可以使用顺序表存储。
对于将数组转为二叉树,有以下特点:
设数组索引为n,左子节点处的索引为2*n+1,右子节点索引为2*n+2,父节点索引为(n-1)/2。
public class Main {
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(0);
System.out.println();
System.out.println("中序遍历结果为:");
tree.infixOrder(0);
System.out.println();
System.out.println("后序遍历结果为:");
tree.postOrder(0);
System.out.println();
}
}
//顺序存储二叉树
class ArrBinaryTree {
private int[] arr;
public ArrBinaryTree(int[] arr) {
this.arr = arr;
}
//前序遍历
public void preOrder(int index) {
if (this.arr == null || this.arr.length == 0) {
System.out.println("数组为空,无法构建二叉树");
return;
}
System.out.print(arr[index] + " ");
//遍历左子树
if ((index * 2 + 1) < this.arr.length) {
preOrder((index * 2 + 1));
}
//遍历右子树
if ((index * 2 + 2) < this.arr.length) {
preOrder((index * 2 + 2));
}
}
//中序遍历
public void infixOrder(int index) {
if (this.arr == null || this.arr.length == 0) {
System.out.println("数组为空,无法构建二叉树");
return;
}
//遍历左子树
if ((index * 2 + 1) < this.arr.length) {
infixOrder((index * 2 + 1));
}
System.out.print(arr[index] + " ");
//遍历右子树
if ((index * 2 + 2) < this.arr.length) {
infixOrder((index * 2 + 2));
}
}
//后序遍历
public void postOrder(int index) {
if (this.arr == null || this.arr.length == 0) {
System.out.println("数组为空,无法构建二叉树");
return;
}
//遍历左子树
if ((index * 2 + 1) < this.arr.length) {
postOrder((index * 2 + 1));
}
//遍历右子树
if ((index * 2 + 2) < this.arr.length) {
postOrder((index * 2 + 2));
}
System.out.print(arr[index] + " ");
}
}
前序遍历结果为:
1 2 4 5 3 6 7
中序遍历结果为:
4 2 5 1 6 3 7
后序遍历结果为:
4 5 2 6 7 3 1