树的序列化与反序列化
一句话说明
序列化就是把树压成字符串,反序列化就是按同样的遍历顺序把它拆回来。
Go 代码:前序方案
type Codec struct{}
func Constructor() Codec {
return Codec{}
}
func (c *Codec) serialize(root *TreeNode) string {
if root == nil {
return "null"
}
return strconv.Itoa(root.Val) + "," + c.serialize(root.Left) + "," + c.serialize(root.Right)
}
func (c *Codec) deserialize(data string) *TreeNode {
vals := strings.Split(data, ",")
idx := 0
var build func() *TreeNode
build = func() *TreeNode {
if vals[idx] == "null" {
idx++
return nil
}
val, _ := strconv.Atoi(vals[idx])
idx++
root := &TreeNode{Val: val}
root.Left = build()
root.Right = build()
return root
}
return build()
}为什么要带 null
没有空指针标记,树的结构信息就会丢失,反序列化时无法唯一还原。