代码拉取完成,页面将自动刷新
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);
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。