把二叉树打印成多行
从上到下按层打印成多行
分析:
使用队列
public class PrintTreeInLines<Key extends Comparable<Key>> {
private class Node {
public Key key;
public Node left, right;
public Node(Key key) {
this.key = key;
}
}
public void print(Node node) {
if (node == null) {
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(node);
int nextLevel = 0; // 下一层结点数
int printed = 1; // 当前层没有打印的结点数
while (!queue.isEmpty()) {
Node current = queue.peek();
System.out.printf("%d\t", current.key);
if (current.left != null) {
queue.add(current.left);
++nextLevel;
}
if (current.right != null) {
queue.add(current.right);
++nextLevel;
}
queue.remove();
--printed;
if (printed == 0) {
System.out.println("");
printed = nextLevel;
nextLevel = 0;
}
}
}
}
网友评论