Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit d82259b

Browse files
committed
257. Binary Tree Paths
1 parent 16eb9e3 commit d82259b

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

257. Binary Tree Paths.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 257. Binary Tree Paths
2+
3+
### 2017-03-21
4+
5+
Given a binary tree, return all root-to-leaf paths.
6+
7+
For example, given the following binary tree:
8+
9+
```
10+
1
11+
/ \
12+
2 3
13+
\
14+
5
15+
16+
```
17+
18+
All root-to-leaf paths are:
19+
20+
```
21+
["1->2->5", "1->3"]
22+
```
23+
24+
25+
26+
# Solution
27+
28+
```swift
29+
/**
30+
* Definition for a binary tree node.
31+
* public class TreeNode {
32+
* public var val: Int
33+
* public var left: TreeNode?
34+
* public var right: TreeNode?
35+
* public init(_ val: Int) {
36+
* self.val = val
37+
* self.left = nil
38+
* self.right = nil
39+
* }
40+
* }
41+
*/
42+
class Solution {
43+
func binaryTreePaths(_ root: TreeNode?) -> [String] {
44+
guard let n = root else { return [] }
45+
var path = [String]()
46+
if n.left == nil && n.right == nil { return ["\(n.val)"]}
47+
for p in binaryTreePaths(n.left) {
48+
path.append("\(n.val)->\(p)")
49+
}
50+
for p in binaryTreePaths(n.right) {
51+
path.append("\(n.val)->\(p)")
52+
}
53+
return path
54+
}
55+
}
56+
```
57+

0 commit comments

Comments
 (0)