-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathUberSerial.java
executable file
·122 lines (90 loc) · 3.16 KB
/
UberSerial.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Algorithms;
// Anything you type or change here will be seen by the other person in real time.
import java.util.Stack;
import org.apache.commons.lang3.StringEscapeUtils;
class UberSerial {
static String splitString = "\"";
static class TreeNode {
// Here.
String val;
TreeNode left;
TreeNode right;
TreeNode(String x) {
//System.out.println(x);
val = x;
left = null;
right = null;
}
}
Stack<TreeNode> stack = new Stack<>();
// We may use other things to sperate the strings instead of the SPACE .
public static void main(String[] str) {
UberSerial codec = new UberSerial();
// TEST CASES
// 1
// 2 3
// 4 # # 5
//# # # #
TreeNode root = new TreeNode("1\"'");
root.left = new TreeNode("2");
root.right = new TreeNode("3");
root.left.left = new TreeNode("4");
root.right.right = new TreeNode("5");
String encodeString = codec.serialize(root);
System.out.printf("\n\nEncode:\n%s\n", encodeString);
TreeNode decodedTree = codec.deserialize(encodeString);
System.out.printf("\n\nAFTER Decode:\n");
// Print the tree..
codec.printTree(decodedTree);
String encodeString2 = codec.serialize(decodedTree);
System.out.printf("\n\nEncode 2nd:\n%s\n", encodeString2);
}
// sure!
// print the tree
public void printTree(TreeNode root) {
if (root == null) {
return;
}
System.out.println(root.val);
printTree(root.left);
printTree(root.right);
}
// Encode
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
TreeNode cur = root;
stack.push(cur);
while (!stack.isEmpty()) {
cur = stack.pop();
if (cur == null) {
sb.append("#" + splitString);
} else {
String escapeVal = StringEscapeUtils.escapeJava(cur.val);
System.out.printf("print the str after escape: %s\n", escapeVal);
sb.append(escapeVal + splitString);
stack.push(cur.right);
stack.push(cur.left);
}
}
return sb.toString();
}
// Decode.
public TreeNode deserialize(String data) {
// remove the spaces.
String[] arr = data.trim().split(splitString);
int[] pos = new int[1];
return helper(arr, pos);
}
private TreeNode helper(String[] arr, int[] pos) {
String str = arr[pos[0]];
pos[0]++;
if (str.equals("#")) {
return null;
}
// unescape the string.
TreeNode root = new TreeNode(StringEscapeUtils.unescapeJava(str));
root.left = helper(arr, pos);
root.right = helper(arr, pos);
return root;
}
}