Golang代码
package main
import (
"fmt"
"strconv"
"strings"
)
type Treenode struct {
Val int
Left, Right *Treenode
}
func Serialization(node *Treenode) string {
if node == nil {
return "nil"
}
tmp := []string{strconv.Itoa(node.Val)}
tmp = append(tmp, Serialization(node.Left), Serialization(node.Right))
return strings.Join(tmp, ",")
}
func Deserialize(s *[]string) *Treenode {
if (*s)[0] == "nil" {
*s = (*s)[1:]
return nil
}
val, _ := strconv.Atoi((*s)[0])
root := &Treenode{val, nil, nil}
*s = (*s)[1:]
if len(*s) > 0 {
root.Left = Deserialize(s)
}
if len(*s) > 0 {
root.Right = Deserialize(s)
}
return root
}
func main() {
root := Treenode{2, nil, nil}
root.Left = &Treenode{1, nil, nil}
root.Right = &Treenode{3, nil, nil}
res := Serialization(&root)
fmt.Println(res) //2,1,nil,nil,3,nil,nil
node_arr := strings.Split(res, ",")
de_root := Deserialize(&node_arr)
fmt.Println(de_root)
fmt.Println(de_root.Left)
fmt.Println(de_root.Right)
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289829.html