这个数据结构是树状结构,可以参考
import java.util.LinkedList;
import java.util.List;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}
public class test1 {
public static int[] array = {1, 2, 3, 4, 5, 6, 7};
public static List<TreeNode> nodeList = new LinkedList<TreeNode>();
public static void createBinTree() {
for(int i = 0; i < array.length; i++) {
nodeList.add(new TreeNode(array[i]));
}
for(int j = 0; j < array.length/2 - 1; j++) {
nodeList.get(j).left = nodeList.get(j*2 + 1);
nodeList.get(j).right = nodeList.get(j*2 + 2);
}
int lastParent = array.length / 2 - 1;
nodeList.get(lastParent).left = nodeList.get(lastParent*2 + 1);
if(array.length % 2 == 1) {
nodeList.get(lastParent).right = nodeList.get(lastParent*2 + 2);
}
}
public static void inorder(TreeNode root) {
if(root == null)
return;
System.out.print(root.val + " ");
inorder(root.left);
inorder(root.right);
}
public static void main(String[] args) {
createBinTree();
TreeNode root = nodeList.get(0);
inorder(root);
}
}