forked from keep-practicing/leetcode-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree_paths.go
47 lines (38 loc) · 965 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
/*
257. Binary Tree Paths
https://leetcode.com/problems/binary-tree-paths/
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
*/
// time: 2019-01-07
package btp
import "strconv"
// TreeNode Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// recursive
// time complexity: O(n), where n is the nodes number in the tree.
// space complexity: O(h), where h is the height of the tree.
func binaryTreePaths(root *TreeNode) []string {
if root == nil {
return []string{}
}
var res []string
if root.Left == nil && root.Right == nil {
return append(res, strconv.Itoa(root.Val))
}
if root.Left != nil {
for _, i := range binaryTreePaths(root.Left) {
res = append(res, strconv.Itoa(root.Val)+"->"+i)
}
}
if root.Right != nil {
for _, i := range binaryTreePaths(root.Right) {
res = append(res, strconv.Itoa(root.Val)+"->"+i)
}
}
return res
}