【二叉树-4】给定数组生成完全二叉树

题目描述:

给定一个数组,生成一个完全二叉树,也就是将数组的值赋给二叉树的各个节点

思想:
  • 先将数组的值全部转化树节点,并将树节点存储到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);
	}
}

生成的树结构如下:
在这里插入图片描述

打印结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值