把数组中存储的数据构建成二叉树。
根节点循环 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++)
最有一个根节点即parentIndex =array.length / 2 - 1,最后单独处理,因为最后一个根节点可能没有有孩子,如果总数为奇数才有有孩子
java代码如下:
public void createBinTree() {
nodeList = new LinkedList();
// 将一个数组的值依次转换为Node节点
for (int nodeIndex = 0; nodeIndex
nodeList.add(new Node(array[nodeIndex]));
}
// 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树,最后一个根节点可能没有有孩子,如果
//parentIndex<= array.length / 2 - 1, 数组可能越界,只有奇数个节点才不会越界
for (int parentIndex = 0; parentIndex
// 左孩子
nodeList.get(parentIndex).leftChild = nodeList
.get(parentIndex * 2 + 1);
// 右孩子
nodeList.get(parentIndex).rightChild = nodeList
.get(parentIndex * 2 + 2);
}
<