forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Tree] add Solution to PathSum, refactor code style
- Loading branch information
Yi Gu
committed
Mar 31, 2016
1 parent
cbc53ad
commit fe91f0e
Showing
3 changed files
with
41 additions
and
11 deletions.
There are no files selected for viewing
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,30 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/path-sum/ | ||
* Primary idea: recursion | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
* 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 { | ||
if root == nil { | ||
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) | ||
} | ||
} |
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
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