数组表示二叉树:
左节点是2i+1,右节点是2i+2
求该节点的父节点是(i - 1)/2
代码:
public class A012_数组表示二叉树并遍历 {
public static void main(String[] args) {
int[] arr = { 78, 56, 34, 43, 4, 1, 15, 2, 23 };
preOrder(arr, 0);
System.out.println();
midOrder(arr, 0);
System.out.println();
posOrder(arr, 0);
}
private static void preOrder(int[] arr, int i) {//前
if (i >= arr.length)
return;
System.out.print(arr[i] + " ");
preOrder(arr, i * 2 + 1);
preOrder(arr, i * 2 + 2);
}
private static void midOrder(int[] arr, int i) {//中
if (i >= arr.length)
return;
midOrder(arr, i * 2 + 1);
System.out.print(arr[i] + " ");
midOrder(arr, i * 2 + 2);
}
private static void posOrder(int[] arr, int i) {//后
if (i >= arr.length)
return;
posOrder(arr, i * 2 + 1);
posOrder(arr, i * 2 + 2);
System.out.print(arr[i] + " ");
}
}