private static class BinaryTreeNode {
private int val;
private BinaryTreeNode left;
private BinaryTreeNode right;
public BinaryTreeNode() {
}
public BinaryTreeNode(int val) {
this.val = val;
}
@Override
public String toString() {
return val + "";
}
}
public static void print(BinaryTreeNode root) {
if (root == null) {
return;
}
List<BinaryTreeNode> current = new LinkedList<>();
List<BinaryTreeNode> reverse = new LinkedList<>();
int flag = 0;
BinaryTreeNode node;
current.add(root);
while (current.size() > 0) {
// 从最后一个开始取
node = current.remove(current.size() - 1);
System.out.printf("%-3d", node.val);
// 当前是从左往右打印的,那就按从左往右入栈
if (flag == 0) {
if (node.left != null) {
reverse.add(node.left);
}
if (node.right != null) {
reverse.add(node.right);
}
}
// 当前是从右往左打印的,那就按从右往左入栈
else {
if (node.right != null) {
reverse.add(node.right);
}
if (node.left != null) {
reverse.add(node.left);
}
}
if (current.size() == 0) {
flag = 1 - flag;
List<BinaryTreeNode> tmp = current;
current = reverse;
reverse = tmp;
System.out.println();
}
}
}