Skip to content

Commit c0ff1a4

Browse files
committed
Add Serialize and Deserialize a BinaryTree
1 parent c2327b5 commit c0ff1a4

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.LinkedList
2+
import ds.TreeNode
3+
4+
/*
5+
Definition of TreeNode:
6+
7+
data class TreeNode(
8+
var value: Int,
9+
var left: TreeNode? = null,
10+
var right: TreeNode? = null
11+
)
12+
*/
13+
14+
fun serialize(root: TreeNode?): String {
15+
// Perform a preorder traversal to add node values to a list, then convert the
16+
// list to a string.
17+
val serializedList = mutableListOf<String>()
18+
preorderSerialize(root, serializedList)
19+
// Convert the list to a string and separate each value using a comma
20+
// delimiter.
21+
return serializedList.joinToString(",")
22+
}
23+
24+
// Helper function to perform serialization through preorder traversal.
25+
fun preorderSerialize(node: TreeNode?, serializedList: MutableList<String>) {
26+
// Base case: mark null nodes as '#'.
27+
if (node == null) {
28+
serializedList.add("#")
29+
return
30+
}
31+
// Preorder traversal processes the current node first, then the left and right
32+
// children.
33+
serializedList.add(node.value.toString())
34+
preorderSerialize(node.left, serializedList)
35+
preorderSerialize(node.right, serializedList)
36+
}
37+
38+
fun deserialize(data: String): TreeNode? {
39+
// Obtain the node values by splitting the string using the comma delimiter.
40+
val nodeValues = LinkedList<String>(data.split(","))
41+
return buildTree(nodeValues)
42+
}
43+
44+
// Helper function to construct the tree using preorder traversal.
45+
fun buildTree(values: LinkedList<String>): TreeNode? {
46+
val value = values.poll()
47+
// Base case: '#' indicates a null node.
48+
if (value == "#") {
49+
return null
50+
}
51+
// Use preorder traversal processes the current node first, then the left and
52+
// right children.
53+
val node = TreeNode(value.toInt())
54+
node.left = buildTree(values)
55+
node.right = buildTree(values)
56+
return node
57+
}

0 commit comments

Comments
 (0)