-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem-4.java
71 lines (46 loc) · 1.57 KB
/
problem-4.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
/*
Question :
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root),
which serializes the tree into a string, and deserialize(s),
which deserializes the string back into the tree.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
I solved this problem in LeetCode.
So, we just need to implement serialize and deserialize
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return "X,";
String leftTree = serialize(root.left);
String rightTree = serialize(root.right);
return root.val + "," + leftTree + rightTree;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> q = new LinkedList<>();
q.addAll(Arrays.asList(data.split(",")));
return utilDeserialize(q);
}
public TreeNode utilDeserialize(Queue<String> q) {
String newNode = q.poll();
if(newNode.equals("X")) return null;
TreeNode node = new TreeNode(Integer.valueOf(newNode));
node.left = utilDeserialize(q);
node.right = utilDeserialize(q);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));