JZ61 序列化二叉树

序列化二叉树

题目:请实现两个函数,分别用来序列化和反序列化二叉树
 
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。

二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。

例如,我们可以把一个只有根节点为1的二叉树序列化为"1,",然后通过自己的函数来解析回这个二叉树
 
type Codec struct {
    l []string
}

func Constructor() Codec {
    return Codec{}    
}

func rserialize(root *TreeNode, str string) string {
    if root == nil {
        str += "null,"
    } else {
        str += strconv.Itoa(root.Val) + ","
        str = rserialize(root.Left, str)
        str = rserialize(root.Right, str)
    }
    return str
}

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

// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
    l := strings.Split(data, ",")
    for i := 0; i < len(l); i++ {
        if l[i] != "" {
            this.l = append(this.l, l[i])
        }
    }
    return this.rdeserialize()
}

func (this *Codec) rdeserialize() *TreeNode {
    if this.l[0] == "null" {
        this.l = this.l[1:]
        return nil
    }

    val, _ := strconv.Atoi(this.l[0])
    root := &TreeNode{Val: val}
    this.l = this.l[1:]
    root.Left = this.rdeserialize()
    root.Right = this.rdeserialize()
    return root
}
 
原文地址:https://www.cnblogs.com/dingxiaoqiang/p/14642762.html