1 Star 0 Fork 1

dllearn/geektime-algorithm-learn

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
f.go 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
dryyun 提交于 2022-04-26 17:41 +08:00 . 0297
package serializeanddeserializebinarytree
import (
"strconv"
"strings"
. "gitee.com/dllearn/geektime-algorithm-learn/structures"
)
// 297. 二叉树的序列化与反序列化
// https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Codec struct {
builder strings.Builder
input []string
}
func Constructor() Codec {
return Codec{}
}
// Serializes a tree to a single string.
func (this *Codec) serialize(root *TreeNode) string {
if root == nil {
this.builder.WriteString("#,")
return ""
}
this.builder.WriteString(strconv.Itoa(root.Val) + ",")
this.serialize(root.Left)
this.serialize(root.Right)
return this.builder.String()
}
// Deserializes your encoded data to tree.
func (this *Codec) deserialize(data string) *TreeNode {
if len(data) == 0 {
return nil
}
this.input = strings.Split(data, ",")
return this.deserializeHelper()
}
func (this *Codec) deserializeHelper() *TreeNode {
if this.input[0] == "#" {
this.input = this.input[1:]
return nil
}
val, _ := strconv.Atoi(this.input[0])
this.input = this.input[1:]
return &TreeNode{
Val: val,
Left: this.deserializeHelper(),
Right: this.deserializeHelper(),
}
}
/**
* Your Codec object will be instantiated and called as such:
* ser := Constructor();
* deser := Constructor();
* data := ser.serialize(root);
* ans := deser.deserialize(data);
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dllearn/geektime-algorithm-learn.git
git@gitee.com:dllearn/geektime-algorithm-learn.git
dllearn
geektime-algorithm-learn
geektime-algorithm-learn
55fa3f222b36

搜索帮助