Skip to content

Commit 738bfcd

Browse files
committed
Time: 285 ms (56%), Space: 40.4 MB (70.77%) - LeetHub
1 parent a85b6ed commit 738bfcd

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.util.ArrayDeque
2+
import java.util.LinkedList
3+
import java.util.Queue
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* class TreeNode(var `val`: Int) {
8+
* var left: TreeNode? = null
9+
* var right: TreeNode? = null
10+
* }
11+
*/
12+
13+
class Codec {
14+
// Encodes a URL to a shortened URL.
15+
fun serialize(root: TreeNode?): String {
16+
if (root == null)
17+
return "[]"
18+
19+
val result = mutableListOf<Int?>()
20+
21+
val queue: Queue<TreeNode?> = LinkedList()
22+
queue += root
23+
24+
var nonNullCount = 1
25+
while (queue.isNotEmpty() && nonNullCount > 0) {
26+
nonNullCount = 0
27+
repeat(queue.size) {
28+
val now = queue.poll()
29+
30+
result += now?.`val`
31+
32+
if (now == null) {
33+
return@repeat
34+
}
35+
36+
for (child in arrayOf(now.left, now.right)) {
37+
queue.add(child)
38+
if (child != null)
39+
nonNullCount += 1
40+
}
41+
}
42+
}
43+
44+
return result.joinToString(",", "[", "]")
45+
}
46+
47+
// Decodes your encoded data to tree.
48+
fun deserialize(data: String): TreeNode? {
49+
if (data == "[]")
50+
return null
51+
52+
val dataList = data.slice(1 until data.lastIndex)
53+
.split(',')
54+
.map { it.toIntOrNull() }
55+
56+
var pointer = 0
57+
val root = TreeNode(dataList[pointer++]!!)
58+
59+
val queue: Queue<TreeNode> = ArrayDeque()
60+
queue += root
61+
62+
while (queue.isNotEmpty() && pointer < dataList.size) {
63+
val now = queue.poll()
64+
65+
val leftVal = dataList[pointer++]
66+
val rightVal = dataList[pointer++]
67+
68+
if (leftVal != null) {
69+
val left = TreeNode(leftVal)
70+
now.left = left
71+
queue += left
72+
}
73+
74+
if (rightVal != null) {
75+
val right = TreeNode(rightVal)
76+
now.right = right
77+
queue += right
78+
}
79+
}
80+
81+
return root
82+
}
83+
}
84+
85+
/**
86+
* Your Codec object will be instantiated and called as such:
87+
* var ser = Codec()
88+
* var deser = Codec()
89+
* var data = ser.serialize(longUrl)
90+
* var ans = deser.deserialize(data)
91+
*/

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy