golang力扣leetcode 297.二叉树的序列化与反序列化

297.二叉树的序列化与反序列化

题解

题目:给你一个二叉树,序列化从一个string字符串,再从一个string字符串还原出二叉树

思路:

1.序列化:前序遍历,根左右
2.反序列化:递归,根左右

代码

type TreeNode struct {
          
   
	Val   int
	Left  *TreeNode
	Right *TreeNode
}
type Codec struct{
          
   }

func Constructor() (_ Codec) {
          
   
	return
}

func (Codec) serialize(root *TreeNode) string {
          
   
	ss := make([]string, 0)
	var dfs func(*TreeNode)
	dfs = func(root *TreeNode) {
          
   
		if root == nil {
          
   
			ss = append(ss, "null")
			return
		}
		ss = append(ss, strconv.Itoa(root.Val))
		dfs(root.Left)
		dfs(root.Right)
	}
	dfs(root)
	return strings.Join(ss, ",")
}

func (Codec) deserialize(data string) *TreeNode {
          
   
	ss := strings.Split(data, ",")
	var build func() *TreeNode
	build = func() *TreeNode {
          
   
		if ss[0] == "null" {
          
   
			ss = ss[1:]
			return nil
		}
		val, _ := strconv.Atoi(ss[0])
		ss = ss[1:]
		return &TreeNode{
          
   val, build(), build()}
	}
	return build()
}
经验分享 程序员 微信小程序 职场和发展