-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathSum.js
More file actions
56 lines (51 loc) · 1.08 KB
/
pathSum.js
File metadata and controls
56 lines (51 loc) · 1.08 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
/**
* Definition for binary tree
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root
* @param {number} sum
* @returns {boolean}
*/
var hasPathSum = function(root, sum) {
if (!root) return false;
if (root.val == sum && root.left == null && root.right == null) {
return true;
}
if (root.left) {
if (hasPathSum(root.left, sum - root.val)) {
return true;
}
}
if (root.right) {
if (hasPathSum(root.right, sum - root.val)) {
return true;
}
}
return false;
};
var assert = require('assert');
var a = new TreeNode(5);
var b = new TreeNode(4);
var c = new TreeNode(8);
var d = new TreeNode(11);
var e = new TreeNode(13);
var f = new TreeNode(4);
var g = new TreeNode(7);
var h = new TreeNode(2);
var i = new TreeNode(1);
a.left = b;
a.right = c;
b.left = d;
c.left = e;
c.right = f;
d.left = g;
d.right = h;
f.right = i;
assert(hasPathSum(a, 22));
assert(hasPathSum(a, 2) === false);
assert(hasPathSum(a, 18));
assert(hasPathSum(null, 2) === false);