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()
}
相关推荐
一只鱼^_2 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
Wzx1980124 小时前
go基础语法练习
开发语言·后端·golang
夏鹏今天学习了吗5 小时前
【LeetCode热题100(64/100)】搜索旋转排序数组
算法·leetcode·职场和发展
alphaTao6 小时前
LeetCode 每日一题 2025/11/3-2025/11/9
windows·leetcode
RedJACK~17 小时前
Go Ebiten小游戏开发:扫雷
开发语言·后端·golang
研究司马懿18 小时前
【ETCD】ETCD——confd配置管理
数据库·golang·自动化·运维开发·etcd·argocd·gitops
小安同学iter21 小时前
SQL50+Hot100系列(11.7)
java·算法·leetcode·hot100·sql50
谈笑也风生1 天前
只出现一次的数字 II(一)
数据结构·算法·leetcode
aloha_7891 天前
测试开发工程师面经准备(sxf)
java·python·leetcode·压力测试
im_AMBER1 天前
Leetcode 47
数据结构·c++·笔记·学习·算法·leetcode