Complete the code to create a new node with the given value.
func NewNode(val int) *TreeNode {
return &TreeNode{Val: [1]
}The function should return a pointer to a TreeNode with the value set to the input val.
Complete the code to append a string to the builder during serialization.
func serializeHelper(root *TreeNode, sb *strings.Builder) {
if root == nil {
sb.WriteString("#,")
return
}
sb.WriteString(strconv.Itoa([1]))
sb.WriteString(",")
serializeHelper(root.Left, sb)
serializeHelper(root.Right, sb)
}We need to convert the current node's value to string and append it. So root.Val is correct.
Fix the error in the deserialization code to correctly parse the next token.
func deserializeHelper(tokens *[]string, index *int) *TreeNode {
if *index >= len(*tokens) {
return nil
}
val := (*tokens)[*index]
[1]
if val == "#" {
return nil
}
num, _ := strconv.Atoi(val)
node := &TreeNode{Val: num}
node.Left = deserializeHelper(tokens, index)
node.Right = deserializeHelper(tokens, index)
return node
}In Go, to increment the value pointed by a pointer, use *index += 1. The syntax *index++ is invalid.
Fill both blanks to complete the code that splits the serialized string and starts deserialization.
func deserialize(data string) *TreeNode {
tokens := strings.Split(data, [1])
index := 0
return deserializeHelper(&tokens, [2])
}The serialized string uses commas to separate tokens, so split by ",". The helper needs a pointer to index, so pass &index.
Fill all three blanks to complete the Serialize function that returns the serialized string.
func Serialize(root *TreeNode) string {
var sb [1]
serializeHelper(root, &sb)
result := sb.[2]()
return result[:len(result)-[3]]
}Use strings.Builder to build the string. Call String() to get the string. Remove the last comma, so subtract 1.