Converts an array of binary tree
注意:补全二叉树的所有节点,缺失节点用null代替
import java.util.ArrayList;
import java.util.List;
public class CreateNode {
public static List<TreeNode> list = new ArrayList<TreeNode>();
public static List<TreeNode> createTree(Integer[] array) {
for (int i = 0; i < array.length; i++) {
TreeNode TreeNode = new TreeNode(array[i], null, null);
list.add(TreeNode);
}
if (list.size() > 0) {
for (int i = 0; i < array.length / 2 - 1; i++) {
if (list.get(2 * i + 1).val != null) {
list.get(i).left = list.get(2 * i + 1);
}
if (list.get(2 * i + 2).val != null) {
list.get(i).right = list.get(2 * i + 2);
}
}
int lastIndex = array.length / 2 - 1;
list.get(lastIndex).left = list.get(lastIndex * 2 + 1);
if (array.length % 2 == 1) {
list.get(lastIndex).right = list.get(lastIndex * 2 + 2);
}
}
return list;
}
public static void print(TreeNode TreeNode) {
if (TreeNode != null) {
System.out.print(TreeNode.val + " ");
print(TreeNode.left);
print(TreeNode.right);
}
}
public static void main(String[] args) {
Integer[] array = { 1, null, 2, null, null, 3 };
CreateNode.createTree(array);
print(list.get(0));
}
}