给出一个我的实现,目前用了几个都对~
public static TreeNode build(Integer[] vals) {
int valid_vals_size = vals.length;
Queue<TreeNode> queue = new LinkedList<>();
LinkedList<Integer> level_order_traveresal =
new LinkedList<>(Arrays.asList(vals));
TreeNode root = new TreeNode(vals[0]);
queue.add(root);
valid_vals_size--;
int index = 0;
while (true) {
TreeNode poll = queue.poll();
int left_index = 2 * index + 1;
int right_index = 2 * index + 2;
if (poll == null) {
level_order_traveresal.add(left_index, null);
level_order_traveresal.add(right_index, null);
} else {
if (left_index >= level_order_traveresal.size()) {
break;
}
Integer left_node = level_order_traveresal.get(left_index);
if (left_node != null) {
poll.left = new TreeNode(left_node);
valid_vals_size--;
}
queue.add(poll.left);
if (right_index >= level_order_traveresal.size()) break;
Integer right_node = level_order_traveresal.get(right_index);
if (right_node != null) {
poll.right = new TreeNode(right_node);
valid_vals_size--;
}
queue.add(poll.right);
}
index++;
if (valid_vals_size <= 0) break;
}
return root;
}
1
kkkkkrua 2020-04-14 18:43:29 +08:00
Java 是值传递且没有引用传递
反了吧? |
3
forestn 2020-04-14 19:03:34 +08:00 via iPhone
深度优先递归吧?
|
4
Newyorkcity OP @forestn 具体一些?
|
5
zmxnv123 2020-04-14 19:31:34 +08:00
用一个队列存放当前层的 Node.
|
6
luckyrayyy 2020-04-14 19:36:56 +08:00
没看懂你的意思,都为 null 了还便利他的子节点干啥?
|
7
xxdd 2020-04-14 20:41:35 +08:00
/**
* 10 0 * / \ * 5 -3 1-2 * / \ \ * 3 2 11 3-6 * / \ \ * 3 -2 1 7-14 * * @param trees * @return */ public static TreeNode initTreeNode(Integer[] trees, int n) { if(n >= trees.length){ return null; } if(null == trees[n]) { return null; } int l = n * 2 + 1; if(l > trees.length){ return new TreeNode(trees[n],null,null); } TreeNode treeNode = new TreeNode(trees[n],initTreeNode(trees,2*n+1),initTreeNode(trees,2*n+2)); return treeNode; } public static void main(String[] args) { Integer[] arr = {10, 5, -3, 3, 2, null, 11, 3, -2, null, 1}; TreeNode treeNode = initTreeNode(arr, 0); } 以前写的一个工具类 |