一、按层打印二叉树,打印的每一行对应二叉树中的一列
本题的难点是在什么时候进行换行:
我们可以用两个变量进行标识:
last:指向当前层的最右结点
nextLast:指向下一层的的最右结点
那么如何更新last和nextLast的值呢?
相关过程如下:
1.初始化时,last=1,把1放入队列;
2.将1出队,把1的子孩子2,3放入队列,更新nlast=3;
3.nlast更新完之后,打印上一次出队的1,并和last比较,如果相同就打印换行,并更新last=nlast=3;
4.将2出队,把2的子孩子4放入队列,更新nlast=4;
5,nlast更新完以后,打印上一次出队的2,并和last(3)比较,不相同,continue;
6.将3出队,将3的子孩子5,6放入队列,更新nlast=6;
7.nlast更新完以后,打印上一次出队的3,并和last(3)比较, 相同就打印换行,并更新last=nlast=6;
…………
总结就是如下循环:(初始化last=根节点)
1.将A出队,并将A的子孩子入队,更新nlast=A最后入队的子孩子;
2.打印上次出队的家伙A,并和last比较, 如果相同就打印换行,并更新last=nlast,如果 不相同,则continue
二、代码如下(java实现):
package cn.jxau.yuan.cn.jxau.yuan.datastructs;
/**
* Created by 编程只服JAVA on 2016.12.01.
*/
import java.util.LinkedList;
import java.util.Queue;
/**
* 1.利用广度优先遍历打印二叉树
*/
public class PrintBTreeWithLineByBFS {
public static void main(String[] args){
//手工构造二叉树
Node node = new Node(1);
node.leftChildren = new Node(2);
Node l = node.rightChildren = new Node(3);
node.leftChildren.leftChildren = new Node(4);
l.leftChildren = new Node(5);
l.rightChildren = new Node(6);
l.leftChildren.leftChildren = new Node(7);
l.leftChildren.rightChildren = new Node(8);
print(node);
}
/**
* 利用队列按层遍历并打印二叉树
* @param root
*/
public static void print(Node root){
if (root == null){
return;
}
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
//指向当前层的最右结点
Node last = root;
//指向下一层的最右结点
Node nextLast = null;
while(!queue.isEmpty()){
Node pollNode = queue.poll();
pollNode.printNode();
root = pollNode;
if (root.leftChildren != null){
queue.add(root.leftChildren);
nextLast = root.leftChildren;
}
if (root.rightChildren != null){
queue.add(root.rightChildren);
nextLast = root.rightChildren;
}
//更新last指向下一行的最右结点
if (pollNode == last){
last = nextLast;
System.out.println();//换行
}
}
}
static class Node{
private Node leftChildren;
private Node rightChildren;
private int data;
public Node(int data){
this.data = data;
}
public void printNode(){
System.out.print(this.data + " ");
}
}
}
结果如下:
1
2 3
4 5 6
7 8
2 3
4 5 6
7 8