题目
二叉树可以用常规的三种遍历结果来描述其结构,但是不够直观,尤其是二叉树中有重复值的时候,仅通过三种遍历的结果来构造二叉树的真实结构更是难上加难,有时则根本不可能。
给定一颗二叉树的头节点head,已知二叉树节点值的类型为32位整数,请实现一个打印二叉树的函数,可以直观地展示树的形状,也便于画出真实的结构。
代码实现
public class PrintTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data, Node left, Node right) {
this.value = data;
this.left = left;
this.right = right;
}
}
public void printTree(Node head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "H", 17);
System.out.println();
}
//遍历顺序:右子树->根节点->左子树
public void printInOrder(Node head, int height, String to, int len) {
if (head == null) {
return;
}
printInOrder(head.right, height + 1, "v", len);
String val = to + head.value + to;
int lenM = val.length();
int lenL = (len - lenM) / 2;
int lenR = len - lenM - lenL;
val = getSpace(lenL) + val + getSpace(lenR);
System.out.println(getSpace(height * len) + val);
printInOrder(head.left, height + 1, "^", len);
}
//给出任意数量空格的字符串
public String getSpace(int num) {
String space = " ";
StringBuffer buf = new StringBuffer();
for (int i = 0; i < num; i++) {
buf.append(space);
}
return buf.toString();
}
//Test
public static void main(String[] args) {
Node node10 = new Node(10, null, null);
Node node8 = new Node(8, null, null);
Node node9 = new Node(9, null, node10);
Node node4 = new Node(4, null, null);
Node node5 = new Node(5, node8, node9);
Node node6 = new Node(6, null, null);
Node node7 = new Node(7, null, null);
Node node2 = new Node(2, node4, node5);
Node node3 = new Node(3, node6, node7);
Node node1 = new Node(1, node2, node3);
PrintTree pt = new PrintTree();
pt.printTree(node1);
}
}