-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPath Sum II.swift
50 lines (44 loc) · 1.51 KB
/
Path Sum II.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
43
44
45
46
47
48
49
50
// 출처 : LeetCode Path Sum II
// https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3838/
// 풀이 : hogumachu
class Solution {
func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] {
var result: [[Int]] = []
guard let root = root else { return result }
visitNode(root, [root.val], root.val)
func visitNode(_ node: TreeNode, _ arr: [Int], _ sum: Int) {
if sum == targetSum && isLeaf(node) {
result.append(arr)
}
if let left = node.left {
visitNode(left, arr + [left.val], sum + left.val)
}
if let right = node.right {
visitNode(right, arr + [right.val], sum + right.val)
}
}
func isLeaf(_ node: TreeNode) -> Bool{
if node.left == nil && node.right == nil {
return true
} else {
return false
}
}
return result
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/