File tree 1 file changed +61
-0
lines changed
serialize-and-deserialize-binary-tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ # Time Complexity: O(n)
3
+ # Space Complexity: O(n)
4
+ */
5
+ /**
6
+ * Definition for a binary tree node.
7
+ * public class TreeNode {
8
+ * int val;
9
+ * TreeNode left;
10
+ * TreeNode right;
11
+ * TreeNode(int x) { val = x; }
12
+ * }
13
+ */
14
+ public class Codec {
15
+
16
+ static int idx ;
17
+
18
+ // Encodes a tree to a single string.
19
+ public String serialize (TreeNode root ) {
20
+ if (root == null ) return "" ;
21
+
22
+ return dfs (root );
23
+ }
24
+
25
+ private String dfs (TreeNode curr ) {
26
+ if (curr == null ) {
27
+ return "." ;
28
+ }
29
+
30
+ return curr .val + "," + dfs (curr .left ) + "," + dfs (curr .right );
31
+ }
32
+
33
+ // Decodes your encoded data to tree.
34
+ public TreeNode deserialize (String data ) {
35
+ if ("" .equals (data )) return null ;
36
+
37
+ String [] values = data .split ("," );
38
+
39
+ idx = 0 ;
40
+ return dfs2 (values );
41
+ }
42
+
43
+ private TreeNode dfs2 (String [] values ) {
44
+ if ("." .equals (values [idx ])) {
45
+ idx ++;
46
+ return null ;
47
+ }
48
+
49
+ TreeNode curr = new TreeNode (Integer .parseInt (values [idx ]));
50
+ idx ++;
51
+ curr .left = dfs2 (values );
52
+ curr .right = dfs2 (values );
53
+
54
+ return curr ;
55
+ }
56
+ }
57
+
58
+ // Your Codec object will be instantiated and called as such:
59
+ // Codec ser = new Codec();
60
+ // Codec deser = new Codec();
61
+ // TreeNode ans = deser.deserialize(ser.serialize(root));
You can’t perform that action at this time.
0 commit comments