forked from LockGit/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree_path.go
62 lines (56 loc) · 1.05 KB
/
binary_tree_path.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
52
53
54
55
56
57
58
59
60
61
62
/**
* Created by GoLand.
* User: lock
* Date: 2018/8/24
* Time: 09:53
* 返回所有根到叶节点的路径
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
package main
import "fmt"
type PathTree struct {
data int
left *PathTree
right *PathTree
}
func getTreePath(root *PathTree) [][]int {
var res [][] int
var cand [] int
recursiveTreePath(root, cand, res)
return res
}
func recursiveTreePath(root *PathTree, cand []int, res [][]int) {
if root == nil {
return
} else {
cand = append(cand, root.data)
if root.left == nil && root.right == nil {
res = append(res, cand)
fmt.Println(res)
}
recursiveTreePath(root.left, cand, res)
recursiveTreePath(root.right, cand, res)
cand = cand[:len(cand)-1]
}
}
func main() {
tree1 := new(PathTree)
tree2 := new(PathTree)
tree3 := new(PathTree)
tree4 := new(PathTree)
tree1.left = tree2
tree1.right = tree3
tree2.right = tree4
tree1.data = 1
tree2.data = 2
tree3.data = 3
tree4.data = 5
fmt.Println("树的所有路径")
getTreePath(tree1)
}