|
| 1 | +// https://leetcode.com/problems/path-sum-iii/description/?envType=study-plan-v2&envId=leetcode-75 |
| 2 | + |
| 3 | +/** |
| 4 | + * Definition for a binary tree node. |
| 5 | + * class TreeNode { |
| 6 | + * val: number |
| 7 | + * left: TreeNode | null |
| 8 | + * right: TreeNode | null |
| 9 | + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 10 | + * this.val = (val===undefined ? 0 : val) |
| 11 | + * this.left = (left===undefined ? null : left) |
| 12 | + * this.right = (right===undefined ? null : right) |
| 13 | + * } |
| 14 | + * } |
| 15 | + */ |
| 16 | + |
| 17 | +// @ts-nocheck |
| 18 | +const depthFirstPathSumCount = ( |
| 19 | + root: TreeNode | null, |
| 20 | + targetSum: number, |
| 21 | + pathSumMap: Map<TreeNode, number> |
| 22 | +): number[] => { |
| 23 | + if (root === null) return [0, 0]; |
| 24 | + |
| 25 | + pathSumMap.set(root, root.val); |
| 26 | + |
| 27 | + let localPathSumCount = 0; |
| 28 | + |
| 29 | + pathSumMap.forEach((val, key) => { |
| 30 | + if (key !== root) val += root.val; |
| 31 | + if (val === targetSum) localPathSumCount++; |
| 32 | + pathSumMap.set(key, val); |
| 33 | + }); |
| 34 | + |
| 35 | + const [leftTreePathSumCount, leftChildVal] = depthFirstPathSumCount( |
| 36 | + root.left, |
| 37 | + targetSum, |
| 38 | + pathSumMap |
| 39 | + ); |
| 40 | + |
| 41 | + if (leftChildVal) |
| 42 | + pathSumMap.forEach((val, key) => pathSumMap.set(key, val - leftChildVal)); |
| 43 | + |
| 44 | + const [rightTreePathSumCount, rightChildVal] = depthFirstPathSumCount( |
| 45 | + root.right, |
| 46 | + targetSum, |
| 47 | + pathSumMap |
| 48 | + ); |
| 49 | + |
| 50 | + pathSumMap.delete(root); |
| 51 | + |
| 52 | + if (rightChildVal) |
| 53 | + pathSumMap.forEach((val, key) => pathSumMap.set(key, val - rightChildVal)); |
| 54 | + |
| 55 | + return [ |
| 56 | + localPathSumCount + leftTreePathSumCount + rightTreePathSumCount, |
| 57 | + root.val, |
| 58 | + ]; |
| 59 | +}; |
| 60 | + |
| 61 | +const pathSum = (root: TreeNode | null, targetSum: number): number => |
| 62 | + depthFirstPathSumCount(root, targetSum, new Map())[0]; |
0 commit comments