顺序存储二叉树
介绍
从数据存储来看,数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组。
如上图所示,二叉树的结点以数组的方式来存放 arr : [1, 2, 3, 4, 5, 6, 6],那么如何在遍历数组时仍然可以以前序遍历,中序遍历和后序遍历的方式完成结点的遍历?那么就要介绍一下顺序存储二叉树的特点。
特点
顺序二叉树通常只考虑完全二叉树,其特点为:
1、第n个元素的左子节点为 2 * n + 1
2、第n个元素的右子节点为 2 * n + 2
3、第n个元素的父节点为 (n-1) / 2
其中,n表示二叉树中的第几个元素(按0开始编号)
顺序存储二叉树的遍历
一个数组Array(1,2,3,4,5,6,7),要求用二叉树前序遍历、中序遍历和后序遍历的三种方式进行遍历。
完整代码
package ArrayBinaryTree;
public class ArrayBinaryTreeDemo {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
ArrayBinaryTree arrayBinaryTree = new ArrayBinaryTree(arr);
System.out.println("前序遍历:");
arrayBinaryTree.preorder(0);
System.out.println();
System.out.println("中序遍历:");
arrayBinaryTree.infixorder(0);
System.out.println();
System.out.println("后序遍历:");
arrayBinaryTree.postOrder(0);
}
}
class ArrayBinaryTree {
private int[] arr;
public ArrayBinaryTree(int[] arr) {
this.arr = arr;
}
// 编写一个方法完成顺序存储二叉树的前序遍历
// index表示数组的下标
public void preorder(int index) {
if (arr.length == 0 || arr == null) {
System.out.println("数组为空,不能进行前序遍历");
}
// 前序遍历,先输出自己
System.out.print(arr[index] + " ");
//向左递归
if (index * 2 + 1 < arr.length) {
preorder(index * 2 + 1);
}
//向右递归
if (index * 2 + 2 < arr.length) {
preorder(index * 2 + 2);
}
}
// 编写一个方法完成顺序存储二叉树的中序遍历
public void infixorder(int index) {
if (arr.length == 0 || arr == null) {
System.out.println("数组为空,不能进行前序遍历");
}
// 前中序遍历,先向左递归
if (index * 2 + 1 < arr.length) {
infixorder(index * 2 + 1);
}
// 再输出自己
System.out.print(arr[index] + " ");
//再向右递归
if (index * 2 + 2 < arr.length) {
infixorder(index * 2 + 2);
}
}
// 编写一个方法完成顺序存储二叉树的后序遍历
public void postOrder(int index) {
if (arr.length == 0 || arr == null) {
System.out.println("数组为空,不能进行前序遍历");
}
// 前中序遍历,先向左递归
if (index * 2 + 1 < arr.length) {
postOrder(index * 2 + 1);
}
// 再向右递归
if (index * 2 + 2 < arr.length) {
postOrder(index * 2 + 2);
}
// 再输出自己
System.out.print(arr[index] + " ");
}
}