github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/binary-tree-paths_test.go (about) 1 package leetcode 2 3 import ( 4 "fmt" 5 "strconv" 6 "testing" 7 ) 8 9 // 257. 二叉树的所有路径 10 // https://leetcode-cn.com/problems/binary-tree-paths/ 11 12 func TestB(t *testing.T) { 13 lr := TreeNode{Val: 5} 14 l := TreeNode{Val: 2, Right: &lr} 15 r := TreeNode{Val: 3} 16 root := TreeNode{Val: 1, Left: &l, Right: &r} 17 fmt.Println(binaryTreePaths(&root)) 18 } 19 20 // 递归写法 21 func binaryTreePaths(root *TreeNode) []string { 22 if root == nil { 23 return nil 24 } 25 if root.Left == nil && root.Right == nil { 26 return []string{strconv.Itoa(root.Val)} 27 } else { 28 var ret []string 29 if root.Left != nil { 30 c := strconv.Itoa(root.Val) + "->" 31 sub := binaryTreePaths(root.Left) 32 for _, v := range sub { 33 ret = append(ret, c+v) 34 } 35 } 36 if root.Right != nil { 37 c := strconv.Itoa(root.Val) + "->" 38 sub := binaryTreePaths(root.Right) 39 for _, v := range sub { 40 ret = append(ret, c+v) 41 } 42 } 43 return ret 44 } 45 }