@@ -152,7 +152,7 @@ def deserialize(self, data):
152152
153153## 代码
154154
155- - 代码支持:JS,Python, Go, PHP
155+ - 代码支持:JS,Python, Go
156156
157157JS Code:
158158
@@ -258,6 +258,83 @@ class Codec:
258258
259259```
260260
261+ Go Code:
262+
263+ ``` go
264+ /* *
265+ * Definition for a binary tree node.
266+ * type TreeNode struct {
267+ * Val int
268+ * Left *TreeNode
269+ * Right *TreeNode
270+ * }
271+ */
272+
273+ type Codec struct {
274+ }
275+
276+ func Constructor () Codec {
277+ return Codec{}
278+ }
279+
280+ // Serializes a tree to a single string.
281+ func (this *Codec ) serialize (root *TreeNode ) string {
282+ ans := " "
283+ q := []*TreeNode{root} // queue
284+ var cur *TreeNode
285+ for len (q) > 0 {
286+ cur, q = q[0 ], q[1 :]
287+ if cur != nil {
288+ ans += strconv.Itoa (cur.Val ) + " ,"
289+ q = append (q, cur.Left )
290+ q = append (q, cur.Right )
291+ } else {
292+ ans += " #,"
293+ }
294+ }
295+ return ans[:len (ans)-1 ]
296+ }
297+
298+ // Deserializes your encoded data to tree.
299+ func (this *Codec ) deserialize (data string ) *TreeNode {
300+ if data == " #" {
301+ return nil
302+ }
303+
304+ a := strings.Split (data, " ," )
305+ var s string
306+ s, a = a[0 ], a[1 :]
307+ v , _ := strconv.Atoi (s)
308+ root := &TreeNode{Val: v}
309+ q := []*TreeNode{root} // queue
310+ var cur , newNode *TreeNode
311+ for len (a) > 0 {
312+ cur, q = q[0 ], q[1 :] // pop
313+
314+ s, a = a[0 ], a[1 :] // 左子树
315+ if s != " #" {
316+ v , _ := strconv.Atoi (s)
317+ newNode = &TreeNode{Val: v}
318+ cur.Left = newNode
319+ q = append (q, newNode)
320+ }
321+
322+ if len (a) == 0 {
323+ return root
324+ }
325+
326+ s, a = a[0 ], a[1 :] // 右子树
327+ if s != " #" {
328+ v , _ := strconv.Atoi (s)
329+ newNode = &TreeNode{Val: v}
330+ cur.Right = newNode
331+ q = append (q, newNode)
332+ }
333+ }
334+ return root
335+ }
336+ ```
337+
261338** 复杂度分析**
262339
263340- 时间复杂度:$O(N)$,其中 N 为树的节点数。
0 commit comments