import java.util.List;
import java.util.LinkedList;
/**
*完全二叉树的构造
*array={1,2,3,4,5,6,7,8,9}
* 1
* 2 3
* 4 5 6 7
* 8 9
*/
public class BinTreeTraverse{
private static int[] array={1,2,3,4,5,6,7,8,9};
private static List<Node> nodeList=null;
/**
*二叉树节点
*/
private static class Node{
Node leftChild;
Node rightChild;
int data;
/**
*构造方法,实例化Node的时候执行
*/
Node(int newData){
leftChild=null;
rightChild=null;
data=newData;
}
}
/**
*创建二叉树(父节点,左孩子,右孩子)
*/
public static void createBinTree()
{
nodeList=new LinkedList<Node>();
//将array里的数加入到Node的List集合中
for(int i=0;i<array.length;i++){
nodeList.add(new Node(array[i]));
}
//将每个节点的左右孩子赋予给每个节点(第一个for循环次数为二叉树层数)
for(int i=0;i<array.length/2-1;i++){
nodeList.get(i).leftChild=nodeList.get(i*2+1);
nodeList.get(i).rightChild=nodeList.get(i*2+2);
}
//最后一个父节点,可能没有右孩子,所以单独考虑
int lastParentIndex=array.length/2-1;
nodeList.get(lastParentIndex).leftChild=nodeList.get(lastParentIndex*2+1);
if(array.length%2 == 1){
nodeList.get(lastParentIndex).rightChild=nodeList.get(lastParentIndex*2+2);
}
}
public static void main(String[] args){
//创建二叉树
createBinTree();
//获取根节点
Node root=nodeList.get(0);
}
}