二叉树的层次遍历带换行java语言实现

可以使用队列实现二叉树的遍历,LinkedLsit可以看做是一个队列,offer和poll分别是进队列和出队列。队列先入先出的特性实现了层次遍历,先将根节点入队,进入循环(循环条件队列非空),首先从队列中取出一个节点(并打印数据),判断从队列中取出(这是重点)的节点是否有左右儿子,有的话依次入队列;如果队列非空,继续循环,从队列再弹出一个节点(并打印),判断该节点的节点是否有左右儿子,有的话依次入队列;每层遍历结束打印换行要通过两个引用lastNode、nextLevelLastNode实现,两个引用初始化为根节点,循环中引用分别指向当前层的最后一个节点和下一层的最后一个节点,每次入队列时候nextLevelLastNode指向入队的节点,左右儿子入队之后判断当前的节点是否等于lastNode,如果是则打印换行符,并且将lastNode指向下一层最后一个节点,即lastNode=nextLevelLastNode。具体实现如下:

import java.util.LinkedList;

public class BiTree{
	private int data;
	private BiTree leftChild;
	private BiTree rightChild;
	
	//constructor
	public BiTree(){
	}
	
	public BiTree(int data, BiTree leftChild, BiTree rightChild){
		this.data = data;
		this.leftChild = leftChild;
		this.rightChild  = rightChild;
	}
	
	//setLeftChild
	private void setLeftChild(BiTree leftChild){
		this.leftChild = leftChild;
	}
	
	//setRightChild
	private void setRightChild(BiTree rightChild){
		this.rightChild = rightChild;
	}
	
	//getData
	private int getData(){
		return this.data;
	}
	
	//getLeftChild
	private BiTree getLeftChild(){
		return this.leftChild;
	}
	
	//getRightChild
	private BiTree getRightChild(){
		return this.rightChild;
	}
	
	//BFS Traverse
	private void BFSTraverse(){
		LinkedList<BiTree>  queue = new LinkedList<BiTree>();
		
		BiTree curNode = null;
		BiTree lastNode = this;
		BiTree nextLevelLastNode = this;
		
		queue.offer(this);
		while(!queue.isEmpty()){
			curNode = queue.poll();
			System.out.print(curNode.getData()+" ");
			
			if(curNode.getLeftChild() != null){
				queue.offer(curNode.getLeftChild());
				nextLevelLastNode = curNode.getLeftChild();
			}
				
			if(curNode.getRightChild() != null){
				queue.offer(curNode.getRightChild());
				nextLevelLastNode = curNode.getRightChild();
			}
			
			if(lastNode == curNode){
				System.out.print("\n");
				lastNode = nextLevelLastNode;
			}

		}
	}
	
	public static void main(String[] args){
		BiTree treeNode0 = new BiTree(0, null, null);
		BiTree treeNode1 = new BiTree(1, null, null);
		BiTree treeNode2 = new BiTree(2, null, null);
		BiTree treeNode3 = new BiTree(3, null, null);
		BiTree treeNode4 = new BiTree(4, null, null);
		BiTree treeNode5 = new BiTree(5, null, null);
		BiTree treeNode6 = new BiTree(6, null, null);
		
		treeNode0.setLeftChild(treeNode1);
		treeNode0.setRightChild(treeNode2);
		treeNode1.setLeftChild(treeNode3);
		treeNode1.setRightChild(treeNode4);
		treeNode2.setLeftChild(treeNode5);
		treeNode2.setRightChild(treeNode6);
		
		treeNode0.BFSTraverse();
	}
}

猜你喜欢

转载自blog.csdn.net/poetteaes/article/details/80385837
今日推荐