forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializeDeserializeNAryTree.swift
42 lines (35 loc) · 1.1 KB
/
SerializeDeserializeNAryTree.swift
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
/**
* Question Link: https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/
* Primary idea: Preorder
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var children: [TreeNode]
* public init(_ val: Int) {
* self.val = val
* self.children = [TreeNode]()
* }
* }
*/
class SerializeDeserializeNAryTree {
func serialize(_ root: Node?) -> String {
guard let root = root else {
return ""
}
return String(root.val) + String(root.children.count) + root.children.map { serialize($0) }.joined()
}
func deserialize(_ vals: inout String) -> Node? {
guard let rootVal = Int(String(vals.removeFirst())) else {
return nil
}
let root = Node(rootVal), size = String(vals.removeFirst())
for _ in 0..<Int(size)! {
if let child = deserialize(&vals) {
root.children.append(child)
}
}
return root
}
}