-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathbinary_tree_paths.go
51 lines (46 loc) · 932 Bytes
/
binary_tree_paths.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
package binary_tree_paths
import (
"strconv"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type solution struct {
path []*TreeNode
ret []string
}
func binaryTreePaths(root *TreeNode) []string {
if root == nil {
return []string{}
}
s := &solution{path: []*TreeNode{root}}
s.helper()
return s.ret
}
func (this *solution) helper() {
if len(this.path) == 0 {
return
}
root := this.path[len(this.path)-1]
if root.Left == nil && root.Right == nil {
s := strconv.Itoa(this.path[0].Val)
for i := 1; i < len(this.path); i++ {
s += "->" + strconv.Itoa(this.path[i].Val)
}
this.ret = append(this.ret, s)
return
}
if root.Left != nil {
this.path = append(this.path, root.Left)
this.helper()
this.path = this.path[:len(this.path)-1]
}
if root.Right != nil {
this.path = append(this.path, root.Right)
this.helper()
this.path = this.path[:len(this.path)-1]
}
return
}