forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPathSum.swift
30 lines (28 loc) · 800 Bytes
/
PathSum.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
/**
* Question Link: https://leetcode.com/problems/path-sum/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* 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
* }
* }
*/
class PathSum {
func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool {
guard let root = root else {
return false
}
if sum == root.val && root.left == nil && root.right == nil {
return true
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
}
}