创建一个String类型的数组
1.创建需要的节点Node
public static class Node{ private Node left; private Node right; private String data; public Node(String newdata) { left = null; right = null; data = newdata; } }
2.创建需要插入的数据
String[] data={"1","2","3","4","5","6"};
3.将数据转换为节点类,并用集合进行封装
List<Node> list = new ArrayList<>(); for(int i=0;i<data.length;i++){ list.add(new Node(data[i])); }
4.创建二叉树
//编写一个创建的方法 public static void creat(LinkedList<Node> list) { for (int i = 0; i < list.size() / 2 - 1; i++) { list.get(i).left = list.get(i * 2 + 1); list.get(i).right = list.get(i * 2 + 2); } //正对最后一个节点单独进行判断 list.get(list.size() / 2 - 1).left = list.get(list.size() - 1); if (list.size() % 2 == 1) { list.get(list.size() / 2 - 1).right = list.get(list.size()); } }