-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0666-path-sum-iv.js
More file actions
56 lines (45 loc) · 1.57 KB
/
0666-path-sum-iv.js
File metadata and controls
56 lines (45 loc) · 1.57 KB
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
/**
* Path Sum Iv
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var pathSum = function (nums) {
const nodeValuesMap = new Map();
for (const currentNum of nums) {
const nodeDepthValue = Math.floor(currentNum / 100);
const nodePositionValue = Math.floor((currentNum % 100) / 10);
const nodeActualValue = currentNum % 10;
const mapIdentifier = `${nodeDepthValue}-${nodePositionValue}`;
nodeValuesMap.set(mapIdentifier, nodeActualValue);
}
function calculatePathSum(levelNumber, positionIndex, currentPathTotal) {
const nodeKeyString = `${levelNumber}-${positionIndex}`;
if (!nodeValuesMap.has(nodeKeyString)) {
return 0;
}
const nodeDataValue = nodeValuesMap.get(nodeKeyString);
const accumulatedSum = currentPathTotal + nodeDataValue;
const nextLevel = levelNumber + 1;
const leftNodeIndex = positionIndex * 2 - 1;
const rightNodeIndex = positionIndex * 2;
const leftKeyString = `${nextLevel}-${leftNodeIndex}`;
const rightKeyString = `${nextLevel}-${rightNodeIndex}`;
const isLeftChildPresent = nodeValuesMap.has(leftKeyString);
const isRightChildPresent = nodeValuesMap.has(rightKeyString);
if (!isLeftChildPresent && !isRightChildPresent) {
return accumulatedSum;
}
const sumFromLeftBranch = calculatePathSum(
nextLevel,
leftNodeIndex,
accumulatedSum,
);
const sumFromRightBranch = calculatePathSum(
nextLevel,
rightNodeIndex,
accumulatedSum,
);
return sumFromLeftBranch + sumFromRightBranch;
}
return calculatePathSum(1, 1, 0);
};