-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112-path-sum.js
More file actions
35 lines (28 loc) · 913 Bytes
/
Copy path112-path-sum.js
File metadata and controls
35 lines (28 loc) · 913 Bytes
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
const { arrayToTree, treeToString } = require('./array-to-tree.js');
var hasPathSum = function(root, targetSum) {
if (!root) return false;
targetSum -= root.val;
if (targetSum === 0 && !root.left && !root.right) return true;
if (hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum)) return true;
targetSum += root.val;
return false;
};
const data = [
{
root: arrayToTree([1,2]),
targetSum: 1,
output: false
},
{
root: arrayToTree([-2,null,-3]),
targetSum: -5,
output: true
},
];
for (let d of data) {
console.log(treeToString(d.root));
const result = hasPathSum(d.root, d.targetSum);
console.log(`targetSum = ${d.targetSum}, result = ${JSON.stringify(result)}, expectedResult = ${JSON.stringify(d.output)}`);
JSON.stringify(result) === JSON.stringify(d.output) ? console.log('ok') : console.error('nok');
console.log('----------');
}