leetcode-257 二叉树的所有路径

257. 二叉树的所有路径

难度: 简单




  • 考察递归, 此题为 Google 的面试题之一

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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {

var res []string

if root == nil {
return res
}

if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
}

tmpLeft := binaryTreePaths(root.Left)
for i := 0; i < len(tmpLeft); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpLeft[i])
}

tmpRight := binaryTreePaths(root.Right)
for i := 0; i < len(tmpRight); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpRight[i])
}
return res

}

文章目录