-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.go
45 lines (38 loc) · 829 Bytes
/
solution.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
package main
import (
"fmt"
"strconv"
)
// TreeNode is a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func binaryTreePaths(root *TreeNode) []string {
var result []string
if root == nil {
return result
}
var temp string
result = dfs(root, temp, result)
return result
}
func dfs(root *TreeNode, temp string, result []string) []string {
temp = temp + strconv.Itoa(root.Val)
if root.Left == nil && root.Right == nil {
result = append(result, temp)
return result
}
if root.Left != nil {
result = dfs(root.Left, temp+"->", result)
}
if root.Right != nil {
result = dfs(root.Right, temp+"->", result)
}
return result
}
func main() {
t := &TreeNode{1, &TreeNode{2, &TreeNode{5, nil, nil}, nil}, &TreeNode{3, nil, nil}}
fmt.Printf("%#v", binaryTreePaths(t))
}