forked from nibnait/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintBinaryTree.java
More file actions
73 lines (60 loc) · 1.96 KB
/
PrintBinaryTree.java
File metadata and controls
73 lines (60 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package Standard;
/**
* 打印二叉树
*
* Created by nibnait on 2016/9/15.
*/
public class PrintBinaryTree {
private static final int NODE_LENGTH = 17; //二叉树中每个节点的长度
public static void print(Node head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "*");
System.out.println();
}
private static void printInOrder(Node head, int height, String to) {
if (head == null){
return;
}
printInOrder(head.left, height+1, "~");
String val = to + head.value + to;
int lenM = val.length();
int lenL = (NODE_LENGTH - lenM) / 2;
int lenR = NODE_LENGTH - lenL - lenM;
val = getSpace(height*NODE_LENGTH + lenL) + val + getSpace(lenR);
System.out.println(val);
printInOrder(head.right, height+1, "_");
}
private static String getSpace(int n) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
sb.append(" ");
}
return sb.toString();
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(-222222222);
head.right = new Node(3);
head.left.left = new Node(Integer.MIN_VALUE);
head.right.left = new Node(55555555);
head.right.right = new Node(66);
head.left.left.right = new Node(777);
print(head);
head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.right.left = new Node(5);
head.right.right = new Node(6);
head.left.left.right = new Node(7);
print(head);
head = new Node(1);
head.left = new Node(1);
head.right = new Node(1);
head.left.left = new Node(1);
head.right.left = new Node(1);
head.right.right = new Node(1);
head.left.left.right = new Node(1);
print(head);
}
}