順序存儲的做法是:把二叉樹按層序(自上而下、自左而右)編號,編號為 i 的結點放進數組下標 i-1 的位置,父子關係靠下標運算推出來,不需要額外的指針。
這種方式只有在完全二叉樹上才划算。因為完全二叉樹的編號天然對應一組連續下標,既不浪費空間,又能直接算出親子關係。普通的二叉樹如果硬要用數組存,就必須按完全二叉樹的形狀補上大量並不存在的「虛擬結點」,空間開銷急劇上升。
圖1 二叉樹順序存儲
約定結點從 1 開始編號,則結點 i 的左孩子是 2*i,右孩子是 2*i+1,父節點是 i/2;不存在的位置填 0。
順手回顧兩條性質:非空二叉樹第 k 層最多有 2k-1 個結點;高度為 h 的二叉樹最多有 2h-1 個結點。
先按高度把樹初始化起來,並提供一個判斷結點是否存在的工具方法:
public class ArrayBiTree<T> {
private Object[] data;
private int height = 3; // 樹的高度,默認3
private int n; // 結點個數
public ArrayBiTree() {
data = new Object[(int) Math.pow(2, height)];
init();
}
/** 指定深度初始化一個樹 */
public ArrayBiTree(int height) {
this.height = height;
data = new Object[(int) Math.pow(2, height) - 1];
}
private void init() {
System.out.println("默認生成一顆完全二叉樹,高度為3:");
for (int i = 0; i < (int) Math.pow(2, height) - 1; i++) {
data[i] = i + 1;
n++;
}
print();
}
/** 判斷結點是否存在,index 從 1 開始 */
public boolean isExist(int index) {
if (index > n) return false;
return Integer.valueOf(data[index - 1].toString()) != 0;
}
}
層序遍歷本質上是廣度優先,用隊列最自然:根節點入隊,出隊時訪問,再把存在的左右孩子編號依次入隊。
/** 層次遍歷,利用隊列實現 */
public void levelOrder() {
RingBuffer<Integer> queue = new RingBuffer<Integer>(n + 1);
queue.put(1); // 根節點先進隊列
while (queue.size() > 0) {
int tmp = queue.get();
System.out.print(data[tmp - 1] + " ");
if (isExist(2 * tmp)) {
queue.put(2 * tmp); // 左孩子存在則入隊
}
if (isExist(2 * tmp + 1)) {
queue.put(2 * tmp + 1); // 右孩子存在則入隊
}
}
}
/** 先序遍歷,遞歸實現 */
public void preOrderRecur(int index) {
if (isExist(index)) {
System.out.print(data[index - 1] + " "); // 訪問根
preOrderRecur(2 * index); // 遞歸左子樹
preOrderRecur(2 * index + 1); // 遞歸右子樹
}
}
用棧模擬函數調用:根入棧,彈出即訪問,右孩子先入棧、左孩子後入棧,這樣左子樹才會先被處理。
/** 先序遍歷,非遞歸實現,借助棧 */
public void preOrder() {
ArrayStack<Integer> stack = new ArrayStack<Integer>(n);
stack.push(1);
while (!stack.isEmpty()) {
int tmp = stack.pop();
System.out.print(data[tmp - 1] + " ");
if (isExist(2 * tmp + 1)) {
stack.push(2 * tmp + 1); // 右子樹編號入棧
}
if (isExist(2 * tmp)) {
stack.push(2 * tmp); // 左子樹編號入棧
}
}
}
另一種寫法更貼近遞歸的思維:一路往左下走並沿途入棧,走到沒有左孩子時彈棧,轉向它的右孩子。
/** 先序遍歷,非遞歸實現 */
public void preOrderOne(int index) {
ArrayStack<Integer> stack = new ArrayStack<Integer>(n);
while (isExist(index) || !stack.isEmpty()) {
// (1) 一路向左下,沿途訪問並入棧
while (isExist(index)) {
System.out.print(data[index - 1] + " ");
stack.push(index);
index = 2 * index;
}
// (2) 棧頂元素的右孩子是否存在
if (!stack.isEmpty()) {
int tmp = stack.pop();
index = 2 * tmp + 1;
}
}
}
/** 中序遍歷,遞歸實現 */
public void inOrderRecur(int index) {
if (isExist(index)) {
inOrderRecur(2 * index); // 左子樹
System.out.print(data[index - 1] + " "); // 訪問根
inOrderRecur(2 * index + 1); // 右子樹
}
}
與先序的非遞歸寫法幾乎一致,只是把「訪問」的時機從出棧前挪到了彈棧那一刻。
/** 中序遍歷,非遞歸實現,更改訪問時機即可 */
public void inOrder(int index) {
ArrayStack<Integer> stack = new ArrayStack<Integer>(n);
while (isExist(index) || !stack.isEmpty()) {
while (isExist(index)) {
stack.push(index);
index = 2 * index;
}
if (!stack.isEmpty()) {
int tmp = stack.pop();
System.out.print(data[tmp - 1] + " ");
index = 2 * tmp + 1;
}
}
}
/** 後序遍歷,遞歸實現 */
public void postOrderRecur(int index) {
if (isExist(index)) {
postOrderRecur(2 * index);
postOrderRecur(2 * index + 1);
System.out.print(data[index - 1] + " ");
}
}
後序麻煩在於根節點必須等左右子樹都處理完,因此額外引入一個 visited 變量記錄「上一次被訪問的結點」,用來判斷右子樹是否已經走過。
/** 後序遍歷,非遞歸實現 */
public void postOrder(int index) {
ArrayStack<Integer> stack = new ArrayStack<Integer>(n);
int visited = 0; // 標記前一個已被訪問的結點
while (isExist(index) || !stack.isEmpty()) {
while (isExist(index)) {
stack.push(index);
index = 2 * index; // 先把左孩子全部找到
}
int top = stack.peek(); // 查看棧頂但不彈出
// 沒有右孩子,或右孩子已訪問過,才能訪問當前結點
if (!isExist(2 * top + 1) || (2 * top + 1) == visited) {
int tmp = stack.pop();
System.out.print(data[tmp - 1] + " ");
visited = tmp;
} else {
index = 2 * top + 1; // 否則先處理右孩子
}
}
}
public static void main(String[] args) {
ArrayBiTree<Integer> biTree = new ArrayBiTree<Integer>();
System.out.print("先序遍歷(遞歸):");
biTree.preOrderRecur(1);
System.out.print("\n中序遍歷(遞歸):");
biTree.inOrderRecur(1);
System.out.print("\n後序遍歷(遞歸):");
biTree.postOrderRecur(1);
System.out.print("\n層次遍歷:");
biTree.levelOrder();
System.out.print("\n先序遍歷(非遞歸):");
biTree.preOrder();
System.out.print("\n中序遍歷(非遞歸):");
biTree.inOrder(1);
System.out.print("\n後序遍歷(非遞歸):");
biTree.postOrder(1);
System.out.println();
biTree.stdIn();
}
把遞歸和非遞歸的結果並排跑一遍,是最快驗證棧模擬是否正確的方法。牢記三條口訣:先序「訪問即可出棧,右先左後」;中序「一路向左入棧,彈出時訪問」;後序「多一個指針記住來路」。