Printing a Binary Tree Hierarchy Using a 2D Array

It's just a simple demo. When learning a binary tree, it is more conducive to learning if you can see a graphical binary tree. It is more intuitive to view the pre-order, mid-continuation, follow-up, and layer-order traversal.
 
 
public class Node {
	Node left;
	Node right;
	int value;

	public Node(int value) {
		this.value = value;
	}
/**
	 * Simulate a matrix with a height of tree height h and a length of 2 to the power of h-1, fill the matrix with elements, print the matrix, and print empty where the matrix is ​​not reassigned
	 */
	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;//If there is only a root element, the length is 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);
		}
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325564173&siteId=291194637