顺序存储二叉树
简介
数组存储方式和树的存储方式可以相互转换,即数组可以转换成树,树也可以转换成数组。
示意图
特点
- 顺序二叉树通常只考虑完全二叉树
- 第n个元素的左子节点为 2 * n + 1
- 第n个元素的右子节点为 2 * n + 2
- 第n个元素的父节点为 (n-1) / 2
- n : 表示二叉树中的第几个元素按0开始编号
需求:给一个数组{1,2,3,4,5,6,7},要求以二叉树前序遍历的方式进行遍历。
代码
class ArrBinaryTree {
private final int[] arr;
public ArrBinaryTree(int[] arr) {
this.arr = arr;
}
//前序遍历
public void preorder(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空,无法遍历");
return;
}
System.out.println(arr[index]);
if (index * 2 + 1 < arr.length) {
preorder(index * 2 + 1);
}
if (index * 2 + 2 < arr.length) {
preorder(index * 2 + 2);
}
}
//中序遍历
public void inorder(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空,无法遍历");
return;
}
if (index * 2 + 1 < arr.length) {
inorder(index * 2 + 1);
}
System.out.println(arr[index]);
if (index * 2 + 2 < arr.length) {
inorder(index * 2 + 2);
}
}
//后序遍历
public void postorder(int index) {
if (arr == null || arr.length == 0) {
System.out.println("数组为空,无法遍历");
return;
}
if (index * 2 + 1 < arr.length) {
postorder(index * 2 + 1);
}
if (index * 2 + 2 < arr.length) {
postorder(index * 2 + 2);
}
System.out.println(arr[index]);
}
}
测试
int[] arr = {1,2,3,4,5,6,7};
ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
System.out.println("=========前序遍历========");
arrBinaryTree.preorder(0);
System.out.println("=========中序遍历========");
arrBinaryTree.inorder(0);
System.out.println("=========后序遍历========");
arrBinaryTree.postorder(0);