順序存儲二叉樹的遍歷
順序存儲的二叉樹通常情況只考慮完全二叉樹
第n個元素的左子節點是:2*n+1
第n個元素的右子節點是:2*n+2
第n個元素的父節點是:(n-1)/2
代碼展示
package demo6;
public class ArrayBinaryTree {
int[] data;
public ArrayBinaryTree(int[] data){
this.data = data;
}
public void frontShow(){
frontShow(0);
}
//前序遍歷
public void frontShow(int index){
if(data==null || data.length==0){
return;
}
//先遍歷當前節點的內容
System.out.print(data[index]+" ");
//處理左子樹:2*index+1
if(2*index+1<data.length){
frontShow(2*index+1);
}
//處理右子樹:2*index+2
if(2*index+2<data.length){
frontShow(2*index+2);
}
}
public void midShow(){
midShow(0);
}
//中序遍歷
public void midShow(int index){
if(data==null || data.length==0){
return;
}
//處理左子樹:2*index+1
if(2*index+1<data.length){
midShow(2*index+1);
}
//遍歷當前節點的內容
System.out.print(data[index]+" ");
//處理右子樹:2*index+2
if(2*index+2<data.length){
midShow(2*index+2);
}
}
public void afterShow(){
afterShow(0);
}
//後序遍歷
public void afterShow(int index){
if(data==null || data.length==0){
return;
}
//左子樹遍歷:2*index+1
if(2*index+1<data.length){
afterShow(2*index+1);
}
//右子樹遍歷:2*index+2
if(2*index+2<data.length){
afterShow(2*index+2);
}
//遍歷當前節點的內容
System.out.print(data[index]+" ");
}
}
package demo6;
public class TestBinaryTree {
public static void main(String[] args) {
int[] data = new int[]{1,2,3,4,5,6,7};
ArrayBinaryTree tree = new ArrayBinaryTree(data);
//前序遍歷
System.out.println("前序遍歷:");
tree.frontShow();
//中序遍歷
System.out.println();
System.out.println("中序遍歷:");
tree.midShow();
//後序遍歷
System.out.println();
System.out.println("後序遍歷:");
tree.afterShow();
}
}