AcWing 50. Go题解 序列化二叉树
原题链接
困难
go 代码
func serialize(root *TreeNode) string {
str := ""
if root == nil {
str += "#,"
return str
} else {
str += strconv.Itoa(root.Val) + ","
}
str += serialize(root.Left)
str += serialize(root.Right)
return str
}
func deserialize(data string) *TreeNode {
if len(data) == 0 {
return nil
}
str := strings.Split(data, ",")
index := -1
return deserializeTree(str, &index)
}
func deserializeTree(str []string, index *int) *TreeNode {
*index++
if *index >= len(str) {
return nil
}
if str[*index] == "#" {
return nil
}
value, _ := strconv.Atoi(str[*index])
node := &TreeNode{
Val: value,
Left: deserializeTree(str, index),
Right: deserializeTree(str, index),
}
return node
}