Skip to content

Commit 9416bd5

Browse files
authored
serialize and deserialize binary tree solution
1 parent cac2aa6 commit 9416bd5

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
10+
type Codec struct {
11+
12+
}
13+
14+
func Constructor() Codec {
15+
return Codec{}
16+
}
17+
18+
// Serializes a tree to a single string.
19+
func (this *Codec) serialize(root *TreeNode) string {
20+
if root == nil {
21+
return ""
22+
}
23+
type Pair struct {
24+
node *TreeNode
25+
path string
26+
}
27+
queue := []Pair{{node: root, path: "1"}}
28+
var tokens []string
29+
for len(queue) != 0 {
30+
u := queue[0]
31+
queue = queue[1:]
32+
tokens = append(tokens, fmt.Sprintf("%s:%d", u.path, u.node.Val))
33+
if u.node.Left != nil {
34+
queue = append(queue, Pair{node: u.node.Left, path: u.path + "0"})
35+
}
36+
if u.node.Right != nil {
37+
queue = append(queue, Pair{node: u.node.Right, path: u.path + "1"})
38+
}
39+
}
40+
return strings.Join(tokens, ",")
41+
}
42+
43+
// Deserializes your encoded data to tree.
44+
func (this *Codec) deserialize(data string) *TreeNode {
45+
if data == "" {
46+
return nil
47+
}
48+
nodes := map[string]*TreeNode{}
49+
for _, token := range strings.Split(data, ",") {
50+
values := strings.Split(token, ":")
51+
path := values[0]
52+
nodeVal, _ := strconv.Atoi(values[1])
53+
nodes[path] = &TreeNode{Val: nodeVal}
54+
if path == "1" {
55+
continue
56+
}
57+
if path[len(path) - 1] == '0' {
58+
nodes[path[: len(path) - 1]].Left = nodes[path]
59+
} else {
60+
nodes[path[: len(path) - 1]].Right = nodes[path]
61+
}
62+
}
63+
return nodes["1"]
64+
}
65+
66+
67+
/**
68+
* Your Codec object will be instantiated and called as such:
69+
* ser := Constructor();
70+
* deser := Constructor();
71+
* data := ser.serialize(root);
72+
* ans := deser.deserialize(data);
73+
*/

0 commit comments

Comments
 (0)