Skip to content

Commit 2011d54

Browse files
sangam14saiyam1814
authored andcommitted
Create binary_tree_paths.go
1 parent a19957c commit 2011d54

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package binary_tree_paths
2+
3+
import (
4+
"strconv"
5+
)
6+
7+
type TreeNode struct {
8+
Val int
9+
Left *TreeNode
10+
Right *TreeNode
11+
}
12+
13+
type solution struct {
14+
path []*TreeNode
15+
ret []string
16+
}
17+
18+
func binaryTreePaths(root *TreeNode) []string {
19+
if root == nil {
20+
return []string{}
21+
}
22+
s := &solution{path: []*TreeNode{root}}
23+
s.helper()
24+
return s.ret
25+
}
26+
27+
func (this *solution) helper() {
28+
if len(this.path) == 0 {
29+
return
30+
}
31+
root := this.path[len(this.path)-1]
32+
if root.Left == nil && root.Right == nil {
33+
s := strconv.Itoa(this.path[0].Val)
34+
for i := 1; i < len(this.path); i++ {
35+
s += "->" + strconv.Itoa(this.path[i].Val)
36+
}
37+
this.ret = append(this.ret, s)
38+
return
39+
}
40+
if root.Left != nil {
41+
this.path = append(this.path, root.Left)
42+
this.helper()
43+
this.path = this.path[:len(this.path)-1]
44+
}
45+
if root.Right != nil {
46+
this.path = append(this.path, root.Right)
47+
this.helper()
48+
this.path = this.path[:len(this.path)-1]
49+
}
50+
return
51+
}

0 commit comments

Comments
 (0)