-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathTreeUtil.java
100 lines (83 loc) · 2.87 KB
/
TreeUtil.java
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
92
93
94
95
96
97
98
99
100
package util;
import java.util.LinkedList;
import java.util.Queue;
/**
* Title:
* Desc:
* Created by Myth on 5/12/2019
*/
public class TreeUtil {
public static String treeNodeToString(TreeNode root) {
if (root == null) {
return "[]";
}
String output = "";
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while(!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.remove();
if (node == null) {
output += "null, ";
continue;
}
output += String.valueOf(node.val) + ", ";
nodeQueue.add(node.left);
nodeQueue.add(node.right);
}
return "[" + output.substring(0, output.length() - 2) + "]";
}
// 按层赋值,空节点使用null 即可 [8,8,7,9,2,null,null,null,null,4,7]
public static TreeNode stringToTreeNode(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return null;
}
String[] parts = input.split(",");
String item = parts[0];
TreeNode root = new TreeNode(Integer.parseInt(item));
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
int index = 1;
while(!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.remove();
if (index == parts.length) {
break;
}
item = parts[index++];
item = item.trim();
if (!item.equals("null")) {
int leftNumber = Integer.parseInt(item);
node.left = new TreeNode(leftNumber);
nodeQueue.add(node.left);
}
if (index == parts.length) {
break;
}
item = parts[index++];
item = item.trim();
if (!item.equals("null")) {
int rightNumber = Integer.parseInt(item);
node.right = new TreeNode(rightNumber);
nodeQueue.add(node.right);
}
}
return root;
}
public static void prettyPrintTree(TreeNode node, String prefix, boolean isLeft) {
if (node == null) {
System.out.println("Empty tree");
return;
}
if (node.right != null) {
prettyPrintTree(node.right, prefix + (isLeft ? "│ " : " "), false);
}
System.out.println(prefix + (isLeft ? "└── " : "┌── ") + node.val);
if (node.left != null) {
prettyPrintTree(node.left, prefix + (isLeft ? " " : "│ "), true);
}
}
public static void prettyPrintTree(TreeNode node) {
prettyPrintTree(node, "", true);
}
}