/**
*
* @ClassName: Tree
* @Description: (二叉树)
* @author Administrator
* @date 2018年5月31日 下午10:59:00
*
*/
public class Tree {
private int []arr= {1,2,3,4,5,6,7,8,9,10};
//集合
private static List<Node> nodeList=null;
//结点
private static class Node {
Node leftchild;
Node rightchild;
int data;
Node(int newdata) {
leftchild = null;
rightchild = null;
data = newdata;
}
}
public void createBintree() {
// 新建一个二叉树
nodeList = new LinkedList<Node>();
for (int nodIndex = 0; nodIndex < arr.length; nodIndex++) {
nodeList.add(new Node(arr[nodIndex]));
}
//左孩子,右孩子
for (int parentIndex = 0; parentIndex < arr.length / 2 - 1; parentIndex++) {
//左
nodeList.get(parentIndex).leftchild=nodeList.get(parentIndex * 2 + 1);
//右孩子
nodeList.get(parentIndex).rightchild=nodeList.get(parentIndex*2+2);
}
int lastParentIndex = arr.length / 2 - 1;
//左孩子不一定有
nodeList.get(lastParentIndex).leftchild=nodeList.get(2*lastParentIndex+1);
if(arr.length%2==0) {
nodeList.get(lastParentIndex).rightchild=nodeList.get(lastParentIndex * 2 + 2);
}
}
public static void main(String[] args) {
Tree t=new Tree();
t.createBintree();
System.out.println("创建成功");
}
}