题目描述:
给定一个数组,生成一个完全二叉树,也就是将数组的值赋给二叉树的各个节点
思想:
- 先将数组的值全部转化树节点,并将树节点存储到LinkedList中
- 遍历所有的父节点(除最后一个),然后给其左右孩子赋值(树结点)
- 处理最后一个父节点,因为最后一个父节点可能没有右孩子
注意:
1、父节点数组下标从0到 n/2 -1 ,但是遍历时要小于n/2-1,因为最后一个父节点可能没有右孩子,当n/2-1为奇数时才有右孩子,为偶数时只有左孩子。
2、结点左孩子下标为2n+1,右孩子下标为2n+2。
3、结点个数为n的完全二叉树的深度为|log2(n)|+1(取2的对数,然后向下取整+1)
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);
}
}
生成的树结构如下:
打印结果: