当前位置: 首页 > article >正文

Golang | Leetcode Golang题解之第449题序列化和反序列化二叉搜索树

题目:

题解:

type Codec struct{}

func Constructor() (_ Codec) { return }

func (Codec) serialize(root *TreeNode) string {
    arr := []string{}
    var postOrder func(*TreeNode)
    postOrder = func(node *TreeNode) {
        if node == nil {
            return
        }
        postOrder(node.Left)
        postOrder(node.Right)
        arr = append(arr, strconv.Itoa(node.Val))
    }
    postOrder(root)
    return strings.Join(arr, " ")
}

func (Codec) deserialize(data string) *TreeNode {
    if data == "" {
        return nil
    }
    arr := strings.Split(data, " ")
    var construct func(int, int) *TreeNode
    construct = func(lower, upper int) *TreeNode {
        if len(arr) == 0 {
            return nil
        }
        val, _ := strconv.Atoi(arr[len(arr)-1])
        if val < lower || val > upper {
            return nil
        }
        arr = arr[:len(arr)-1]
        return &TreeNode{Val: val, Right: construct(val, upper), Left: construct(lower, val)}
    }
    return construct(math.MinInt32, math.MaxInt32)
}

http://www.kler.cn/news/336778.html

相关文章:

  • 如何查看NVIDIA Container Toolkit是否配置成功
  • 《数据结构》学习系列——树
  • ssh连接阿里云长连接
  • Django学习笔记十四:系统框架总结
  • 日常记账:解锁生活财务管理的秘密钥匙
  • 大模型应用新领域:探寻终端侧 AI 竞争核心|智于终端
  • Win10 IDEA连接虚拟机中的Hadoop(HDFS)
  • idea配置注释
  • 系统架构设计师-下午案例题(2021年下半年)
  • qt_c++_xml存这种复杂类型
  • ROS基础入门——实操教程
  • Python字符串操作详解
  • 深入探索Vue3组合式API
  • PCL 1.8.1 + VTK 1.8.0 + QT5.14.2+ VS2017 环境搭建
  • 【Ubuntu】Ubuntu常用命令
  • DAY26||669.修建二叉树 |108.将有序数组转换为二叉搜索树|538.把二叉搜索树转换为累加树
  • Spring Validation 参数校验框架
  • 模型漫谈:图神经网络(GNN)是什么样的存在
  • 计算机网络:计算机网络概述:网络、互联网与因特网的区别
  • python常用库总结(argparse、re、matlpotlab.plot)