题解 | #序列化二叉树#一时递归一时爽,一直递归一直爽

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

package main

import (
	"strconv"
	"strings"
)

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

func Serialize(root *TreeNode) string {
	// write code here
	if root == nil {
		return "#"
	}
	return strconv.Itoa(root.Val) + "," + Serialize(root.Left) + "," + Serialize(root.Right)
}
func Deserialize(s string) *TreeNode {
	// write code here
	list := strings.Split(s, ",")
	var travc func()*TreeNode
	travc=func() *TreeNode {
		val:=list[0]
		list=list[1:]
		if val=="#"{
			return nil
		}
		value,_:=strconv.Atoi(val)
		return &TreeNode{value,travc(),travc()}
	}
	return travc()
}
一时递归一时爽,一直递归一直爽
全部评论

相关推荐

中电45所 测试开发岗 可以解决北京户口,提供员工宿舍,早 8 晚 5(不过一般会加班到7-8点,周六一般也会去,面试官说的) 硕士
点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务