-
Notifications
You must be signed in to change notification settings - Fork 5
/
SerializeAndDeserialize.java
107 lines (100 loc) · 2.89 KB
/
SerializeAndDeserialize.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
/*https://leetcode.com/problems/serialize-and-deserialize-binary-tree/*/
public class Codec {
StringBuffer result;
TreeNode root;
int index;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
result = new StringBuffer("");
serPreorder(root);
System.out.println(result);
return result.toString();
}
public void serPreorder(TreeNode root)
{
if (root == null)
result.append("n#");
else
{
result.append(root.val);
result.append("#");
serPreorder(root.left);
serPreorder(root.right);
}
}
public TreeNode deserPreOrder(String[] tokens)
{
if (index == tokens.length) return null;
if (tokens[index].equals("n")) return null;
if (root == null)
{
root = new TreeNode(Integer.parseInt(tokens[index]));
++index;
root.left = deserPreOrder(tokens);
++index;
root.right = deserPreOrder(tokens);
return root;
}
TreeNode newNode = new TreeNode(Integer.parseInt(tokens[index]));
++index;
newNode.left = deserPreOrder(tokens);
++index;
newNode.right = deserPreOrder(tokens);
return newNode;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] tokens = data.split("[#]");
index = 0;
root = deserPreOrder(tokens);
return root;
}
}
/*https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1*/
class Tree
{
StringBuffer result;
Node root;
int index;
public Node deserPreOrder(ArrayList<Integer> tokens)
{
if (index == tokens.size()) return null;
if ((Integer)tokens.get(index) == -1) return null;
if (root == null)
{
root = new Node((Integer)tokens.get(index));
++index;
root.left = deserPreOrder(tokens);
++index;
root.right = deserPreOrder(tokens);
return root;
}
Node newNode = new Node((Integer)tokens.get(index));
++index;
newNode.left = deserPreOrder(tokens);
++index;
newNode.right = deserPreOrder(tokens);
return newNode;
}
//Function to serialize a tree and return a list containing nodes of tree.
public void serialize(Node root, ArrayList<Integer> A)
{
//code here
if (root == null)
A.add(-1);
else
{
A.add(root.data);
serialize(root.left,A);
serialize(root.right,A);
}
}
//Function to deserialize a list and construct the tree.
public Node deSerialize(ArrayList<Integer> A)
{
//code here
index = 0;
root = deserPreOrder(A);
return root;
}
};