Golang | Leetcode Golang题解之第297题二叉树的序列化与反序列化

题目:

题解:

Go 复制代码
type Codec struct{}

func Constructor() (_ Codec) {
    return
}

func (c Codec) serialize(root *TreeNode) string {
    if root == nil {
        return "X"
    }
    left := "(" + c.serialize(root.Left) + ")"
    right := "(" + c.serialize(root.Right) + ")"
    return left + strconv.Itoa(root.Val) + right
}

func (Codec) deserialize(data string) *TreeNode {
    var parse func() *TreeNode
    parse = func() *TreeNode {
        if data[0] == 'X' {
            data = data[1:]
            return nil
        }
        node := &TreeNode{}
        data = data[1:] // 跳过左括号
        node.Left = parse()
        data = data[1:] // 跳过右括号
        i := 0
        for data[i] == '-' || '0' <= data[i] && data[i] <= '9' {
            i++
        }
        node.Val, _ = strconv.Atoi(data[:i])
        data = data[i:]
        data = data[1:] // 跳过左括号
        node.Right = parse()
        data = data[1:] // 跳过右括号
        return node
    }
    return parse()
}
相关推荐
Haohao+++17 分钟前
leetcode面试经典算法题——2
算法·leetcode·面试
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】1534. 统计好三元组
数据结构·算法·leetcode
weixin_445054721 小时前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
Starwow2 小时前
微服务之gRPC
后端·微服务·golang
-优势在我3 小时前
LeetCode之两数之和
算法·leetcode
WaitWaitWait013 小时前
LeetCode每日一题4.17
算法·leetcode
Chandler244 小时前
Go:低级编程
开发语言·后端·golang
冠位观测者4 小时前
【Leetcode 每日一题】2176. 统计数组中相等且可以被整除的数对
数据结构·算法·leetcode
阳洞洞5 小时前
leetcode 213. House Robber II
算法·leetcode·动态规划
梭七y5 小时前
【力扣hot100题】(099)寻找重复数
算法·leetcode·职场和发展