只是一个简单的demo,在学习二叉树时,如果能够看图形化的二叉树是比较有利于学习的。更能直观的查看前序,中续,后续,层序遍历。看到别的地方的二叉树图形化打印过于麻烦,下面提供简单直观的方法,打印二叉树。
public class Node {
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
/**
* 模拟一个高度为树高度h,长度为2的h次方-1的矩阵,将元素填充矩阵,打印矩阵,矩阵没有重新赋值的打印空
*/
public static void print(Node root) {
if (root == null)
return;
int height = treeHeight(root);
int width = (int) (Math.pow(height, 2)) - 1;
width = width > 0 ? width : 1;//如果仅有root元素,则长度为1
Log.println("h=" + height + ";w=" + width);
int[][] square = new int[height][width];
setIndex(square, root, 0, width - 1, 0);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int v = square[i][j];
if (v <= 0) {
Log.print(" ");
} else {
Log.print(v);
}
}
Log.println();
}
}
public static void setIndex(int[][] square, Node roo