题解 | #序列化二叉树#

序列化二叉树

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

```package main
import "strconv"
import "strings"
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param root TreeNode类 
 * @return TreeNode类
*/

func Serialize(root *TreeNode) string {
	if root == nil {
		return "#"
	}
	return strconv.Itoa(root.Val) + "," + Serialize(root.Left) + "," + Serialize(root.Right)
}

func Deserialize(s string) *TreeNode {
	str := strings.Split(s, ",")
	return buildTree(&str)
	
}

func buildTree(s *[]string) *TreeNode {
	rootValue := (*s)[0]
	*s = (*s)[1:]
	if rootValue == "#" {
		return nil
	}
	val, _ := strconv.Atoi(rootValue)
	root := &TreeNode{
		Val:   val,
		Left:  nil,
		Right: nil,
	}
	root.Left = buildTree(s)
	root.Right = buildTree(s)
	return root
}
全部评论

相关推荐

GGrain:没事,本硕985也不发面试笔试😖
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务