/
index.go
70 lines (56 loc) · 1.11 KB
/
index.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
62
63
64
65
66
67
68
69
70
package index
import (
"encoding/json"
"errors"
)
type Codec struct {
}
func Constructor() Codec {
return Codec{}
}
type any=interface{}
func replacer(root *TreeNode) any {
if root == nil {
return nil
}
return []any{root.Val, replacer(root.Left), replacer(root.Right)}
}
// Serializes a tree to a single string.
func (c *Codec) serialize(root *TreeNode) string {
var b, e = json.Marshal(replacer(root))
if e != nil {
panic(e)
}
// fmt.Println(string(b))
return string(b)
}
func reviver(data any) *TreeNode {
// fmt.Println(data)
var vv, ok = data.([]interface{})
// fmt.Println(vv,ok)
if ok {
// fmt.Println( reflect.TypeOf(vv[0]))
var val, ok = (vv[0]).(float64)
// fmt.Println(val,ok)
if ok {
var p = &TreeNode{
Val: int(val),
Left: reviver(vv[1]),
Right: reviver(vv[2])}
return p
} else {
panic(errors.New("type error float64"))
}
}
return nil
}
// Deserializes your encoded data to tree.
func (c *Codec) deserialize(data string) *TreeNode {
var p any
var e = json.Unmarshal([]byte(data), &p)
if e != nil {
panic(e)
}
// fmt.Println(p)
return reviver(p)
}