-
Notifications
You must be signed in to change notification settings - Fork 0
/
606.go
49 lines (43 loc) · 767 Bytes
/
606.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
package p606
import (
"bytes"
"strconv"
)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func tree2str(t *TreeNode) string {
res := new(bytes.Buffer)
var preorder func(node *TreeNode)
preorder = func(node *TreeNode) {
if node == nil {
return
}
res.WriteString(strconv.FormatInt(int64(node.Val), 10))
if node.Left != nil {
res.WriteByte('(')
preorder(node.Left)
res.WriteByte(')')
}
if node.Right != nil {
if node.Left == nil {
res.WriteString("()")
}
res.WriteByte('(')
preorder(node.Right)
res.WriteByte(')')
}
}
preorder(t)
return res.String()
}