利用二维数组打印二叉树层次结构

只是一个简单的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 root, int begin, int end, int high) {
		int mid = (begin + end) / 2;
		square[high][mid] = root.value;
		if (root.left != null) {
			setIndex(square, root.left, begin, mid - 1, high + 1);
		}
		if (root.right != null) {
			setIndex(square, root.right, mid + 1, end, high + 1);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/github_37235807/article/details/80222292