-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0297-serialize-and-deserialize-binary-tree.kt
64 lines (51 loc) · 1.38 KB
/
0297-serialize-and-deserialize-binary-tree.kt
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
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Codec() {
// Encodes a URL to a shortened URL.
fun serialize(root: TreeNode?): String {
val sb = StringBuilder()
serialize(root, sb)
return sb.toString()
}
// Decodes your encoded data to tree.
fun deserialize(data: String): TreeNode? {
val queue = LinkedList<String>()
for (str in data.split(",")) {
queue.add(str)
}
return deserialize(queue)
}
private fun serialize(root: TreeNode?, sb: StringBuilder) {
if (root == null) {
sb.append("null")
sb.append(",")
return
}
sb.append(root.`val`)
sb.append(",")
serialize(root.left, sb)
serialize(root.right, sb)
}
private fun deserialize(queue: Queue<String>): TreeNode? {
val str = queue.remove()
if (str.equals("null")) {
return null
}
val node = TreeNode(str.toInt())
node.left = deserialize(queue)
node.right = deserialize(queue)
return node
}
}
/**
* Your Codec object will be instantiated and called as such:
* var ser = Codec()
* var deser = Codec()
* var data = ser.serialize(longUrl)
* var ans = deser.deserialize(data)
*/