문제: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
null이면 #을 넣어 직렬화하였습니다.
class Codec {
func serialize(_ root: TreeNode?) -> String {
var queue = [root]
var result = [String]()
while !queue.isEmpty {
let node = queue.removeFirst()
if node == nil {
result.append("#")
} else {
queue.append(node!.left)
queue.append(node!.right)
result.append(String(node!.val))
}
}
return result.joined(separator: " ")
}
func deserialize(_ data: String) -> TreeNode? {
let nodes = data.split(separator: " ").map { String($0) }
if nodes[0] == "#" { return nil }
let root = TreeNode(Int(nodes[0])!)
var queue = [root]
var index = 1
while !queue.isEmpty {
let node = queue.removeFirst()
if nodes[index] != "#" {
node.left = TreeNode(Int(nodes[index])!)
queue.append(node.left!)
}
index += 1
if nodes[index] != "#" {
node.right = TreeNode(Int(nodes[index])!)
queue.append(node.right!)
}
index += 1
}
return root
}
}
'알고리즘' 카테고리의 다른 글
[Swift] LeetCode - 136. Single Number (0) | 2022.02.17 |
---|---|
[Swift] LeetCode - 1038. Binary Search Tree to Greater Sum Tree (0) | 2022.02.17 |
[Swift] LeetCode - 207. Course Schedule (0) | 2022.02.16 |
[Swift] LeetCode - 78. Subsets (0) | 2022.02.16 |
[Swift] LeetCode - 39. Combination Sum (0) | 2022.02.16 |
댓글