-
Notifications
You must be signed in to change notification settings - Fork 887
/
SerializeDeserializeBinaryTree.swift
103 lines (85 loc) · 2.7 KB
/
SerializeDeserializeBinaryTree.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Question Link: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
* Primary idea: Preorder or level order
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
# Solution 1 - Preorder
class SerializeDeserializeBinaryTree {
func serialize(_ root: Node?) -> String {
guard let root = root else {
return "#"
}
return String(root.val) + serialize(root.left) + serialize(root.right)
}
func deserialize(_ vals: inout String) -> Node? {
guard let rootVal = Int(String(vals.removeFirst())) else {
return nil
}
let root = Node(rootVal)
root.left = deserialize(&vals)
root.right = deserialize(&vals)
return root
}
}
# Solution 2 - Level order, BFS
class SerializeDeserializeBinaryTree {
func serialize(_ root: Node?) -> String {
guard let root = root else {
return ""
}
var res = "", nodes: [Node?] = [root]
while !nodes.isEmpty {
let currentLevelSize = nodes.count
for _ in 0..<currentLevelSize {
let node = nodes.removeFirst()
if let node = node {
res.append(String(node.val))
nodes.append(node.left)
nodes.append(node.right)
} else {
res.append("#")
}
}
}
return res
}
func deserialize(_ vals: String) -> Node? {
guard let firstVal = vals.first, let rootVal = Int(String(firstVal)) else {
return nil
}
let root = Node(rootVal), vals = Array(vals)
var nodes: [Node?] = [root], i = 1
while !nodes.isEmpty {
guard let node = nodes.removeFirst() else {
continue
}
var left: Node?
if let leftVal = Int(String(vals[i])) {
left = Node(leftVal)
}
node.left = left
nodes.append(left)
i += 1
var right: Node?
if let rightVal = Int(String(vals[i])) {
right = Node(rightVal)
}
node.right = right
nodes.append(right)
i += 1
}
return root
}
}