建議先實現二叉樹
一、什麼是順序存儲二叉樹
基本說明
從數據存儲來看,數組存儲方式和樹的存儲方式可以相互轉換,即數組可以轉換成樹,樹也可以轉換成數組
要求
- 二叉樹的結點能夠以數組的方式來存放 arr: [1,2,3,4,5,6,7];
- 遍歷數組時能夠以前序遍歷,中序遍歷,後序遍歷的方式遍歷出所有結點
特點
- 順序二叉樹通常只考慮完全二叉樹
- 第n個元素的左子節點爲 2 * n + 1
- 第n個元素的右子節點爲 2 * n + 2
- 第n個元素的父節點爲 (n-1) / 2
- n : 表示二叉樹中的第幾個元素(按0開始編號,如圖所示)
二、代碼實現
1.前序遍歷
class ArrayBinaryTree {
//存儲數據節點的數組
private int[] array;
public ArrayBinaryTree(int[] array) {
this.array = array;
}
//前序遍歷入口
public void preOrder() {
preOrder(0);
}
/**
* 前序遍歷
* @param index
*/
public void preOrder(int index) {
//如果數組爲空或數組.length==0
if (array == null || array.length == 0) {
System.out.println("數組爲空,不能按照二叉樹的前序遍歷!");
}
//輸出當前這個元素
System.out.print(array[index]+" ");
//向左遞歸遍歷
if ((index * 2 + 1) < array.length) {
preOrder(2 * index + 1);
}
//向右遞歸遍歷
if ((index * 2 + 2) < array.length) {
preOrder(2 * index + 2);
}
}
2.中序遍歷
class ArrayBinaryTree {
//存儲數據節點的數組
private int[] array;
public ArrayBinaryTree(int[] array) {
this.array = array;
}
//中序遍歷入口
public void infixOrder() {
infixOrder(0);
}
/**
* 中序遍歷
* @param index
*/
private void infixOrder(int index) {
//如果數組爲空或數組.length==0
if (array == null || array.length == 0) {
System.out.println("數組爲空,不能按照二叉樹的前序遍歷!");
}
//向左遞歸遍歷
if ((index * 2 + 1) < array.length) {
infixOrder(2 * index + 1);
}
//輸出當前這個元素
System.out.print(array[index]+" ");
//向右遞歸遍歷
if ((index * 2 + 2) < array.length) {
infixOrder(2 * index + 2);
}
}
2.後序遍歷
class ArrayBinaryTree {
//存儲數據節點的數組
private int[] array;
public ArrayBinaryTree(int[] array) {
this.array = array;
}
//後序遍歷入口
public void postOrder() {
infixOrder(0);
}
/**
* 後序遍歷
* @param index
*/
private void postOrder(int index) {
//如果數組爲空或數組.length==0
if (array == null || array.length == 0) {
System.out.println("數組爲空,不能按照二叉樹的前序遍歷!");
}
//向左遞歸遍歷
if ((index * 2 + 1) < array.length) {
postOrder(2 * index + 1);
}
//向右遞歸遍歷
if ((index * 2 + 2) < array.length) {
postOrder(2 * index + 2);
}
//輸出當前這個元素
System.out.print(array[index]+" ");
}
啓動入口
public class ArrayBinaryTreeDemo {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7};
ArrayBinaryTree tree = new ArrayBinaryTree(array);
System.out.println("前序");
tree.preOrder();
System.out.println();
System.out.println("中序");
tree.infixOrder();
System.out.println();
System.out.println("後序");
tree.postOrder();
System.out.println();
}
}