数据结构与算法:二叉树的层次遍历(队列)
public class BinaryTree<E> {
private TreeNode<E> root; //根节点
private List<TreeNode> nodeList = null; //二叉树节点的链式结构
public BinaryTree(){
}
public BinaryTree(TreeNode<E> root){
this.root = root;
}
//层次遍历
public void levelOrder(TreeNode<E> root){
Queue<TreeNode<E>> nodeQueue = new LinkedList<TreeNode<E>>();
TreeNode<E> node = null;
nodeQueue.add(root); //将根节点入队
while(!nodeQueue.isEmpty()){ //队列不空循环
node = nodeQueue.peek();
System.out.print(node.getData()+" ");
nodeQueue.poll(); //队头元素出队
if(node.getLchild() != null){ //左子树不空,则左子树入队列
nodeQueue.add(node.getLchild());
}
if(node.getRchild() != null){ //右子树不空,则右子树入队列
nodeQueue.add(node.getRchild());
}
}
}
}