思路是维护一个节点队列和两个节点引用last(上一行最后的元素).nlast(本行最后的元素),初始化时nlast=last=root。不断取出队列第一个元素x,然后将x的左右孩子入队并移动nlast到最后一个孩子。然后判断x是否是last,是则打印并换行并将last指向nlast(开始下一行),否则普通打印。 文字描述不太清晰,结合程序走一遍就理解了。
package structure;
import java.util.LinkedList;
public class BinaryTreeNode {
private int value;
private BinaryTreeNode leftChild;
private BinaryTreeNode rightChild;
public void print(){
LinkedList<BinaryTreeNode> queue=new LinkedList<>();
queue.add(this);
BinaryTreeNode last=this;
BinaryTreeNode nlast=this;
while(!queue.isEmpty()){
BinaryTreeNode node=queue.poll();
if(node.getLeftChild()!=null){
queue.offer(node.getLeftChild());
nlast=queue.getLast();
}
if(node.getRightChild()!=null){
queue.offer(node.getRightChild());
nlast=queue.getLast();
}
if (node==last) {
System.out.print(node.getValue()+"\n");
last=nlast;
} else {
System.out.print(node.getValue()+" ");
}
}
}
}
public static void main(String[] args){
BinaryTreeNode root=new BinaryTreeNode(1, null, null);
BinaryTreeNode node2=new BinaryTreeNode(2, null, null);
BinaryTreeNode node3=new BinaryTreeNode(3, null, null);
BinaryTreeNode node4=new BinaryTreeNode(4, null, null);
BinaryTreeNode node5=new BinaryTreeNode(5, null, null);
BinaryTreeNode node6=new BinaryTreeNode(6, null, null);
BinaryTreeNode node7=new BinaryTreeNode(7, null, null);
BinaryTreeNode node8=new BinaryTreeNode(8, null, null);
root.setLeftChild(node2);
root.setRightChild(node3);
node2.setLeftChild(node4);
node3.setLeftChild(node5);
node3.setRightChild(node6);
node5.setLeftChild(node7);
node5.setRightChild(node8);
root.print();
}
结果:
1
2 3
4 5 6
7 8