java 二叉树 建立完全二叉树和广度优先遍历

来源:互联网 发布:网络歌曲太多 翻唱 编辑:程序博客网 时间:2024/06/15 16:23

今天想写个如何建立完全二叉树的方法。顺便把二叉树的广度优先遍历也写了下。实这两者思路都相似,都是用队列实现的,先进先出。若有任何问题,敬请指出来!

一.建立完全二叉树思路:

先从根节点开始,判断左右子树是否为空。若为空,将新节点插入子树;若不为空,就把根节点的左右子树入队列,开始下一次循环。从队列中先取出根节点的左子树,判断是否为空,若为空,插入。若不为空,则将其左右子树入队列。依队列顺序再判断根节点的右子树。以此循环。

//建立完全二叉树。
public void addData(int data){
Node newNode = new Node();    //创建新节点对象,并初始化。
newNode.data = data;
newNode.right = null;
newNode.left = null;


LinkedList<Node> queue = new LinkedList<Node>() ;  //用链表实现队列
queue.addFirst(root);        //先把root节点从队列头加入。
while(!queue.isEmpty()){      //队列不为空时,一直循环。
Node node = queue.pollLast();   //从队列尾取出节点。
if(node.left == null){
node.left = newNode;        //若节点左子树为空,就把新节点插入到左子树。
return;
}else if( node.right == null){
node.right = newNode;    //若节点右子树为空,就把新节点插入到右子树。
return;
}
queue.addFirst(node.left);  //否则将左右子树入队列。注意顺序,必须先左后右
queue.addFirst(node.right);
}
}


二、广度优先遍历思路

先从根节点开始,先访问根节点,若左右子树不为空,把左右子树入队列。开始下一轮循环。


//广度优先遍历
public void BFtPrint(){
LinkedList<Node> queue = new LinkedList<Node>() ;
if(root!=null){
queue.addFirst(root);                      //先把root节点从队列头加入。
while(!queue.isEmpty()){
Node node = queue.pollLast();          //从队列尾取出节点。
System.out.print(node.data+",  ");//访问该节点。

//若左右子树不为空,加入队列。注意顺序。
if(node.left!=null){
queue.addFirst(node.left); 
}
if(node.right!=null){
queue.addFirst(node.right);
}
}
}
}


结果如下:



0 0