代码
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
BinaryTree binaryTree = new BinaryTree(arr);
binaryTree.preOrder(0);
System.out.println("----------------");
binaryTree.infixOrder(0);
System.out.println("----------------");
binaryTree.postOrder(0);
System.out.println("----------------");
}
}
class BinaryTree{
int[] arr;
public BinaryTree(int[] arr) {
this.arr = arr;
}
public void preOrder(int index){
if (arr == null || arr.length == 0){
System.out.println("数组为空 无法遍历");
return;
}
if (index < 0 || index > arr.length - 1){
System.out.println("索引index不对");
return;
}
System.out.println(arr[index]);
if (2 * index + 1 >= 0 && 2 * index + 1 < arr.length){
this.preOrder(2 * index + 1);
}
if (2 * (index + 1) >= 0 && 2 * (index + 1) < arr.length){
this.preOrder(2 * (index + 1));
}
}
public void infixOrder(int index){
if (arr == null || arr.length == 0){
System.out.println("数组长度为0 无法遍历");
return;
}
if (index < 0 || index > arr.length - 1){
System.out.println("索引值不对 无法遍历");
return;
}
if (2 * index + 1 < arr.length){
this.infixOrder(2 * index + 1);
}
System.out.println(arr[index]);
if (2 * (index + 1) < arr.length){
this.infixOrder(2 * (index + 1));
}
}
public void postOrder(int index){
if (arr == null || arr.length == 0){
System.out.println("数组长度为0 无法遍历");
return;
}
if (index < 0 || index > arr.length - 1){
System.out.println("索引值不对 无法遍历");
return;
}
if (2 * index + 1 < arr.length){
this.postOrder(2 * index + 1);
}
if (2 * (index + 1) < arr.length){
this.postOrder(2 * (index + 1));
}
System.out.println(arr[index]);
}
}
结果
1
2
4
5
3
6
7
----------------
4
2
5
1
6
3
7
----------------
4
5
2
6
7
3
1
----------------
需要注意的
①用数组顺序存储二叉树,一般是针对完全二叉树
②假如数组某元素的索引为index
,则它左子节点的索引为2 * index + 1
,右子节点的索引为2 * (index + 1)
,当然是在存在的前提下。判断存在的条件也不再是是否为null
,而是看索引值是否越界。比如判断左子节点存在的条件是if (2 * index + 1 < arr.length)