构造完全二叉树


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);
	}
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值