-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpathSum.ts
46 lines (35 loc) · 1.53 KB
/
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
44
45
46
import type { TreeNode } from '~/utils/binary-tree';
type PathSum = (root: TreeNode | null, targetSum: number) => number;
/**
* Accepted
*/
export const pathSum: PathSum = (root, targetSum) => {
// Initialize a counter to track the number of valid paths
let count = 0;
// Helper function for DFS traversal, takes the current node and the path from root to this node
const dfs = (node: TreeNode | null, currentPath: number[]) => {
// Base case: If the current node is null, return (end of path)
if (node === null) return;
// Add the current node's value to the path
currentPath.push(node.val);
// Variable to track the sum of values in the current path
let pathSum = 0;
// Check all sub-paths ending at the current node
// We do this by iterating backward from the current node to the start of the path
for (let i = currentPath.length - 1; i >= 0; i--) {
pathSum += currentPath[i];
// If the sum of any sub-path equals the targetSum, increment the counter
if (pathSum === targetSum) count += 1;
}
// Recursively call DFS on the left and right children of the current node
dfs(node.left, currentPath);
dfs(node.right, currentPath);
// Backtrack: Remove the current node's value from the path before returning
// This ensures that the path remains accurate for other branches of the tree
currentPath.pop();
};
// Start DFS traversal from the root with an empty path
dfs(root, []);
// Return the total number of paths that sum up to targetSum
return count;
};