449. 序列化和反序列化二叉搜索树

序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
编码的字符串应尽可能紧凑。

思路:通法,就是序列化转化,再反序列化回来,递归左右子树

  1. //dfs 前序遍历
  2. type Codec struct {
  3. res []string
  4. }
  5. func Constructor() Codec {
  6. return Codec{}
  7. }
  8. // 序列化树 为单个字符串。
  9. func (this *Codec) serialize(root *TreeNode) string {
  10. if root == nil {
  11. return "#" //nil节点用# 占位
  12. }
  13. return strconv.Itoa(root.Val) + "," + this.serialize(root.Left) + "," + this.serialize(root.Right) //格式转化,数字转化为ACill码,用逗号分隔
  14. }
  15. // 反序列化编码数据 为树。
  16. func (this *Codec) deserialize(data string) *TreeNode {
  17. this.res = strings.Split(data, ",") //以逗号切割,分成几个小部分字符串
  18. return this.dfsDeserialize() //递归1
  19. }
  20. func (this *Codec) dfsDeserialize() *TreeNode {
  21. node := this.res[0] //递归3
  22. this.res = this.res[1:]
  23. if node == "#" {
  24. return nil
  25. }
  26. v, _ := strconv.Atoi(node) //字符串转换为 int类型
  27. root := &TreeNode{
  28. Val: v,
  29. Left: this.dfsDeserialize(), //递归2
  30. Right: this.dfsDeserialize(),
  31. }
  32. return root
  33. }
//bfs解法
type Codec struct {
}

func Constructor() Codec {
    return Codec{}
}

// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
    if root == nil {
        return ""
    }

    var res []string
    var queue = []*TreeNode{root}

    for 0 < len(queue) {
        if queue[0] != nil {
            res = append(res, strconv.Itoa(queue[0].Val))
            queue = append(queue, queue[0].Left, queue[0].Right)

        } else {
            res = append(res, "#")
        }
        queue = queue[1:]
    }
    return strings.Join(res, ",")
}

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
    if len(data) == 0 {
        return nil
    }

    var res = strings.Split(data, ",")
    var root = &TreeNode{}
    root.Val, _ = strconv.Atoi(res[0])

    var queue = []*TreeNode{root}
    res = res[1:]

    for 0 < len(queue) {
        if res[0] != "#" {
            l, _ := strconv.Atoi(res[0])
            queue[0].Left = &TreeNode{Val: l}
            queue = append(queue, queue[0].Left)
        }

        if res[1] != "#" {
            r, _ := strconv.Atoi(res[1])
            queue[0].Right = &TreeNode{Val: r}
            queue = append(queue, queue[0].Right)
        }
        queue = queue[1:]
        res = res[2:]
    }
    return root
}