Created
August 2, 2020 12:42
-
-
Save charlieInDen/67892b914750031f12feb2cfbc36674b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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