-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathSum.ts
43 lines (32 loc) · 916 Bytes
/
pathSum.ts
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
31
32
33
34
35
36
37
38
39
40
41
42
43
import { TreeNode } from 'classes/BinaryTreeNode'
// <Recursion, DFS, Backtracking>
// Time: O(n^2)
// Space: O(n)
// 1. dfs
function dfs(node: TreeNode | null, ans: number[][], path: number[], targetSum: number, sum = 0) {
if (!node) {
return
}
// 2.a backtracking - add the path
path.push(node.val)
sum += node.val
// 2.b backtracking - collect if it's valid
if (!node.left && !node.right && sum === targetSum) {
ans.push(path.slice())
}
dfs(node.left, ans, path, targetSum, sum)
dfs(node.right, ans, path, targetSum, sum)
// 2.c backtracking - remove the path
path.pop()
}
function pathSum(root: TreeNode | null, targetSum: number): number[][] {
// edge cases
if (!root) {
return []
}
const ans: number[][] = []
const path: number[] = []
dfs(root, ans, path, targetSum)
return ans
}
export { pathSum }