-
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.
- Loading branch information
1 parent
b54bb13
commit 9d7ab29
Showing
2 changed files
with
69 additions
and
0 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,27 @@ | ||
from typing import Optional, List | ||
|
||
from trees.TreeNode import TreeNode | ||
|
||
|
||
# O(n) time || O(max(n, log(n)) space | ||
def path_sum(self, root: Optional[TreeNode], target_sum: int) -> List[List[int]]: | ||
res = [] | ||
|
||
def dfs(node, curr_sum, curr_path): | ||
if not node: | ||
return | ||
|
||
curr_sum += node.val | ||
curr_path.append(node.val) | ||
|
||
if not node.left and not node.right and curr_sum == target_sum: | ||
res.append(list(curr_path)) | ||
|
||
dfs(node.left, curr_sum, curr_path) | ||
dfs(node.right, curr_sum, curr_path) | ||
|
||
curr_path.pop() | ||
|
||
dfs(root, 0, []) | ||
|
||
return res |
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,42 @@ | ||
import unittest | ||
|
||
from trees.PathSumII import path_sum | ||
from trees.TreeNode import TreeNode | ||
|
||
|
||
class MyTestCase(unittest.TestCase): | ||
def test_path_sum(self): | ||
root = TreeNode( | ||
val=5, | ||
left=TreeNode( | ||
val=4, | ||
left=TreeNode( | ||
val=11, | ||
left=TreeNode(7), | ||
right=TreeNode(2) | ||
) | ||
), | ||
right=TreeNode( | ||
val=8, | ||
left=TreeNode(13), | ||
right=TreeNode( | ||
val=4, | ||
left=TreeNode(5), | ||
right=TreeNode(1) | ||
) | ||
) | ||
) | ||
self.assertEqual([[5, 4, 11, 2], [5, 8, 4, 5]], path_sum(self, root, 22)) | ||
|
||
def test_path_sum_1(self): | ||
root = TreeNode( | ||
val=1, | ||
left=TreeNode(2), | ||
right=TreeNode(3) | ||
) | ||
|
||
self.assertEqual([], path_sum(self, root, 0)) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |