这个数据结构是树状结构,可以参考
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() {
//并把数组中的值都转化为树结点的值,存储到list中
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);
}
}