-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
LeetCodePlayground.playground/Pages/112_PathSum.xcplaygroundpage/Contents.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
//: [Previous](@previous) | ||
|
||
import Foundation | ||
|
||
|
||
/// 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 Solution { | ||
func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { | ||
guard let root = root else { | ||
return false | ||
} | ||
if root.left == nil && root.right == nil { | ||
return root.val == sum | ||
} | ||
return hasPathSum(root.left, sum - root.val) | ||
|| hasPathSum(root.right, sum - root.val) | ||
} | ||
} | ||
|
||
//: [Next](@next) |