Skip to content

Commit 712773f

Browse files
author
ChienkuChen
committed
Add 297
1 parent 8787982 commit 712773f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package _297;
2+
3+
import datastructure.TreeNode;
4+
5+
import java.util.Arrays;
6+
import java.util.LinkedList;
7+
import java.util.Queue;
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode(int x) { val = x; }
16+
* }
17+
*/
18+
class Codec {
19+
20+
// Encodes a tree to a single string.
21+
public String serialize(TreeNode root) {
22+
if (root == null)
23+
return "null";
24+
25+
return root.val + "," + serialize(root.left) + "," + serialize(root.right);
26+
}
27+
28+
29+
// Decodes your encoded data to tree.
30+
public TreeNode deserialize(String data) {
31+
Queue<String> list = new LinkedList<>(Arrays.asList(data.split(",")));
32+
return deserializeHelp(list);
33+
}
34+
35+
private TreeNode deserializeHelp(Queue<String> queue) {
36+
if (queue.size() == 0)
37+
return null;
38+
39+
String s = queue.poll();
40+
if (s.equals("null"))
41+
return null;
42+
43+
TreeNode root = new TreeNode(Integer.valueOf(s));
44+
root.left = deserializeHelp(queue);
45+
root.right = deserializeHelp(queue);
46+
47+
return root;
48+
}
49+
50+
public static void main(String[] args) {
51+
final Codec codec = new Codec();
52+
System.out.println(codec.serialize(codec.deserialize("1,2,null,null,3,4,5")));
53+
}
54+
}
55+
56+
// Your Codec object will be instantiated and called as such:
57+
// Codec codec = new Codec();
58+
// codec.deserialize(codec.serialize(root));

0 commit comments

Comments
 (0)