二叉树
# 二叉树构建
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static TreeNode construct(int[] arr){
List<TreeNode> list = new ArrayList<>();
TreeNode root = null;
int n = arr.length;
for(int i=0;i<n;i++){
TreeNode node = new TreeNode(arr[i]);
list.add(node);
if(i==0)
root = node; // 构建根节点
}
for(int i=0;i*2+1<n;i++){
TreeNode node = list.get(i);
if(node!=null){
node.left = list.get(i*2+1);
if(i*2+2<n){
node.right = list.get(i*2+2);
}
}
}
return root;
}
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
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