1 顺序存储的二叉树

image-20190928154753006

image-20190928155024127


2 顺序存储的二叉树的遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.println(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);
}
}

}

Test

1
2
3
4
5
6
7
8
9
10
11

public class TestArrayBinaryTree {

public static void main(String[] args) {
int[] data = new int[] {1,2,3,4,5,6,7};
ArrayBinaryTree tree = new ArrayBinaryTree(data);
//前序遍历
tree.frontShow();
}

}