-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem257.swift
42 lines (38 loc) · 1.2 KB
/
problem257.swift
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
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
//pre-order traversal
class Solution {
func binaryTreePaths(_ root: TreeNode?) -> [String] {
var ans = [String]()
if (root == nil) {
return ans
}
var node = [TreeNode](); var path = [String]()
node.append(root!); path.append(String(root!.val))
while (!node.isEmpty) {
let tmp_node = node.removeLast()
let tmp_path = path.removeLast()
if (tmp_node.left != nil || tmp_node.right != nil) {
if (tmp_node.left != nil) {
node.append(tmp_node.left!)
path.append(tmp_path + "->" + String(tmp_node.left!.val))
}
if (tmp_node.right != nil) {
node.append(tmp_node.right!)
path.append(tmp_path + "->" + String(tmp_node.right!.val))
}
} else {
ans.append(tmp_path)
}
}
return ans
}
}