Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created August 2, 2020 10:36
Show Gist options
  • Save charlieInDen/23b756d20ff22b3ee424ff79175d6253 to your computer and use it in GitHub Desktop.
Save charlieInDen/23b756d20ff22b3ee424ff79175d6253 to your computer and use it in GitHub Desktop.
/**
* 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
* }
* }
*/
class Codec {
func postOrder(_ root: TreeNode?, _ output: inout String) {
if root == nil { return }
postOrder(root?.left, &output)
postOrder(root?.right, &output)
output = output + String(root?.val ?? -1) + " "
}
// Encodes a tree to a single string.
func serialize(_ root: TreeNode?) -> String {
var result: String = ""
if root == nil { return result }
postOrder(root, &result)
_ = result.removeLast()
print(result)
return result
}
func deserializeHelper(_ min: Int, _ max: Int,_ postOrder: inout [String]) -> TreeNode? {
if postOrder.isEmpty { return nil }
guard let last = Int(postOrder.last!) else {
print("fail")
return nil
}
if last < min || last > max { return nil }
_ = postOrder.removeLast()
let root = TreeNode(last)
root.right = deserializeHelper(last, max , &postOrder)
root.left = deserializeHelper(min, last, &postOrder)
return root
}
// Decodes your encoded data to tree.
func deserialize(_ data: String) -> TreeNode? {
var post = data.components(separatedBy: " ")
if post.isEmpty { return nil }
return deserializeHelper(Int.min, Int.max, &post)
}
}
/**
* Your Codec object will be instantiated and called as such:
* let obj = Codec()
* val s = obj.serialize(root)
* let ans = obj.serialize(s)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment