Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created August 2, 2020 12:42
Show Gist options
  • Save charlieInDen/67892b914750031f12feb2cfbc36674b to your computer and use it in GitHub Desktop.
Save charlieInDen/67892b914750031f12feb2cfbc36674b to your computer and use it in GitHub Desktop.
class Codec {
func serializeHelper(_ root: TreeNode?,_ output: inout String) {
if root == nil {
output = output + "null" + " "
return
}
output = output + String(root!.val) + " "
serializeHelper(root?.left, &output)
serializeHelper(root?.right, &output)
}
func serialize(_ root: TreeNode?) -> String {
if root == nil { return "" }
var output = ""
serializeHelper(root, &output)
print(output)
return output
}
func deserializehelper(_ result: inout [String]) -> TreeNode? {
if result.isEmpty == true { return nil }
let value = result.removeFirst()
var node: TreeNode?
if value == "null" {
return nil
} else {
node = TreeNode(Int(value)!)
}
node?.left = deserializehelper(&result)
node?.right = deserializehelper(&result)
return node
}
func deserialize(_ data: String) -> TreeNode? {
if data.isEmpty { return nil }
var result = data.components(separatedBy: " ")
return deserializehelper(&result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment