-
Notifications
You must be signed in to change notification settings - Fork 0
/
question48.go
61 lines (48 loc) · 1.24 KB
/
question48.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package chapter08
import (
"strconv"
"strings"
"github.com/syhily/code-interviews/common"
)
const (
delimiter = ","
nilPlacerHolder = "#"
)
var (
atoi = func(s string) int {
r, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return r
}
)
func serializeTreeNode(node *common.TreeNode[int]) string {
return serialize(node, strconv.Itoa)
}
func deserializeTreeNode(text string) *common.TreeNode[int] {
return deserialize(text, atoi)
}
func serialize[T comparable](node *common.TreeNode[T], fn func(T) string) string {
if node == nil {
return nilPlacerHolder
}
return fn(node.Value) + delimiter + serialize(node.Left, fn) + delimiter + serialize(node.Right, fn)
}
func deserialize[T comparable](text string, fn func(string) T) *common.TreeNode[T] {
nodes, start := strings.Split(text, delimiter), 0
return innerDeserialize(nodes, &start, fn)
}
func innerDeserialize[T comparable](nodes []string, start *int, fn func(string) T) *common.TreeNode[T] {
var node *common.TreeNode[T]
text := nodes[*start]
*start++
if text == nilPlacerHolder {
return nil
} else {
node = &common.TreeNode[T]{Value: fn(text)}
}
node.Left = innerDeserialize(nodes, start, fn)
node.Right = innerDeserialize(nodes, start, fn)
return node
}