进行层次遍历时,对一层结点访问完后,再按照它们的访问次序对各个结点的左孩子右孩子顺序访问,这样就完成了对下一层从左往右访问。
具体步骤如下:
(1)初始化一个队列;
(2)将根节点放入队列;
(3)重复步骤4~7直到队列为空;
(4)从队列中取出一个结点x;
(5)访问x;
(6)如果x存在左孩子,将左孩子放入队列;
(7)如果x存在右孩子,将右孩子放入队列;
public void levelorder(BinaryTreeNode node) {
if(node==null)
return;
Queue<BinaryTreeNode> queue=new LinkedList<BinaryTreeNode>();
queue.offer(node);
while(!queue.isEmpty()) {
BinaryTreeNode temp=queue.poll(); //弹出节点
System.out.println(temp.value);
if(temp.left!=null) queue.offer(temp.left);
if(temp.right!=null) queue.offer(temp.right);
}
}