forked from Blankj/awesome-java-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
91 lines (82 loc) · 2.32 KB
/
TreeNode.java
File metadata and controls
91 lines (82 loc) · 2.32 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.blankj.structure;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/06/05
* desc :
* </pre>
*/
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
/**
* 创建测试数据
*
* @param data [XX,XX,null,xx]
* @return {@link TreeNode}
*/
public static TreeNode createTestData(String data) {
if (data.equals("[]")) return null;
data = data.substring(1, data.length() - 1);
String[] split = data.split(",");
int len = len = split.length;
TreeNode[] treeNodes = new TreeNode[len];
data = data.substring(1, data.length() - 1);
for (int i = 0; i < len; i++) {
if (!split[i].equals("null")) {
treeNodes[i] = new TreeNode(Integer.valueOf(split[i]));
}
}
for (int i = 0; i < len; i++) {
if (treeNodes[i] != null) {
int leftIndex = i * 2 + 1;
if (leftIndex < len) {
treeNodes[i].left = treeNodes[leftIndex];
}
int rightIndex = leftIndex + 1;
if (rightIndex < len) {
treeNodes[i].right = treeNodes[rightIndex];
}
}
}
return treeNodes[0];
}
private static final String space = " ";
/**
* 竖向打印二叉树
*
* @param root 二叉树根节点
*/
public static void print(TreeNode root) {
print(root, 0);
}
private static void print(TreeNode node, int deep) {
if (node == null) {
printSpace(deep);
System.out.println("#");
return;
}
print(node.right, deep + 1);
printSpace(deep);
printNode(node.val);
print(node.left, deep + 1);
}
private static void printSpace(int count) {
for (int i = 0; i < count; i++) {
System.out.printf(space);
}
}
private static void printNode(int val) {
StringBuilder res = new StringBuilder(val + "<");
int spaceNum = space.length() - res.length();
for (int i = 0; i < spaceNum; i++) {
res.append(" ");
}
System.out.println(res);
}
}