-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path36-437.ts
62 lines (50 loc) · 1.59 KB
/
36-437.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// https://leetcode.com/problems/path-sum-iii/description/?envType=study-plan-v2&envId=leetcode-75
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
// @ts-nocheck
const depthFirstPathSumCount = (
root: TreeNode | null,
targetSum: number,
pathSumMap: Map<TreeNode, number>
): number[] => {
if (root === null) return [0, 0];
pathSumMap.set(root, root.val);
let localPathSumCount = 0;
pathSumMap.forEach((val, key) => {
if (key !== root) val += root.val;
if (val === targetSum) localPathSumCount++;
pathSumMap.set(key, val);
});
const [leftTreePathSumCount, leftChildVal] = depthFirstPathSumCount(
root.left,
targetSum,
pathSumMap
);
if (leftChildVal)
pathSumMap.forEach((val, key) => pathSumMap.set(key, val - leftChildVal));
const [rightTreePathSumCount, rightChildVal] = depthFirstPathSumCount(
root.right,
targetSum,
pathSumMap
);
pathSumMap.delete(root);
if (rightChildVal)
pathSumMap.forEach((val, key) => pathSumMap.set(key, val - rightChildVal));
return [
localPathSumCount + leftTreePathSumCount + rightTreePathSumCount,
root.val,
];
};
const pathSum = (root: TreeNode | null, targetSum: number): number =>
depthFirstPathSumCount(root, targetSum, new Map())[0];