其他分享
首页 > 其他分享> > 二叉树序列化反序列化

二叉树序列化反序列化

作者:互联网

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)

}

标签:node,Treenode,nil,fmt,二叉树,序列化,root,Left
来源: https://www.cnblogs.com/notomatoes/p/16700212.html