Skip to content

Commit

Permalink
feature: path sum ii
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 16, 2023
1 parent b54bb13 commit 9d7ab29
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
27 changes: 27 additions & 0 deletions trees/PathSumII.py
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
42 changes: 42 additions & 0 deletions trees/test/test_path_sum.py
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()

0 comments on commit 9d7ab29

Please sign in to comment.