Skip to content

Commit 0ba5b3d

Browse files
committed
add: SerializeAndDeserializeABinaryTree
1 parent b0dda08 commit 0ba5b3d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import java.lang.StringBuilder;
2+
import java.util.Arrays;
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
6+
import DS.TreeNode;
7+
8+
/*
9+
// Definition of TreeNode:
10+
class TreeNode {
11+
public int val;
12+
public TreeNode left;
13+
public TreeNode right;
14+
public TreeNode(int val) {
15+
this.val = val;
16+
}
17+
}
18+
*/
19+
20+
public class SerializeAndDeserializeABinaryTree {
21+
public String serialize(TreeNode root) {
22+
// Perform a preorder traversal to add node values to a list, then convert the
23+
// list to a string.
24+
StringBuilder serializedList = new StringBuilder();
25+
preorderSerialize(root, serializedList);
26+
return serializedList.toString();
27+
}
28+
29+
// Helper function to perform serialization through preorder traversal.
30+
private void preorderSerialize(TreeNode node, StringBuilder serializedList) {
31+
// Base case: mark null nodes as '#'.
32+
if (node == null) {
33+
serializedList.append("#").append(",");
34+
return;
35+
}
36+
// Preorder traversal processes the current node first, then the left and right
37+
// children.
38+
serializedList.append(node.val).append(",");
39+
preorderSerialize(node.left, serializedList);
40+
preorderSerialize(node.right, serializedList);
41+
}
42+
43+
public TreeNode deserialize(String data) {
44+
// Obtain the node values by splitting the string using the comma delimiter.
45+
Queue<String> nodeValues = new LinkedList<>();
46+
nodeValues.addAll(Arrays.asList(data.split(",")));
47+
return buildTree(nodeValues);
48+
}
49+
50+
// Helper function to construct the tree using preorder traversal.
51+
private TreeNode buildTree(Queue<String> values) {
52+
String val = values.poll();
53+
// Base case: '#' indicates a null node.
54+
if (val.equals("#")) {
55+
return null;
56+
}
57+
// Use preorder traversal processes the current node first, then the left and
58+
// right children.
59+
TreeNode node = new TreeNode(Integer.valueOf(val));
60+
node.left = buildTree(values);
61+
node.right = buildTree(values);
62+
return node;
63+
}
64+
}

0 commit comments

Comments
 (0)