树 - 二叉树建立
# 非递归构建
public class BinaryTree {
public TreeNode root;
public BinaryTree(int[] array) {
root = createBinaryTree(array, 0);
}
/**
* 创建二叉树
*
* @param array
* @param index
* @return
*/
private TreeNode createBinaryTree(int[] array, int index) {
TreeNode treeNode = null;
if (index < array.length) {
treeNode = new TreeNode(array[index]);
// 对于顺序存储的完全二叉树,如果某个节点的索引为index,
// 其对应的左子树的索引为2 * index + 1,右子树为 2 * index + 2
treeNode.left = createBinaryTree(array, 2 * index + 1);
treeNode.right = createBinaryTree(array, 2 * index + 2);
}
return treeNode;
}
}
class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
super();
this.data = data;
}
@Override
public String toString() {
return data + " ";
}
}
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
35
36
37
38
39
40
41
42
43
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
35
36
37
38
39
40
41
42
43
上次更新: 2023/11/01, 03:11:44