-
Notifications
You must be signed in to change notification settings - Fork 312
/
path-sum-iii.js
53 lines (43 loc) · 920 Bytes
/
path-sum-iii.js
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
// Source : https://leetcode.com/problems/path-sum-iii/
// Author : Han Zichi
// Date : 2016-10-24
// Runtime: 309 ms
"use strict";
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {number}
*/
var pathSum = function(root, sum) {
if (!root)
return 0;
let ans = 0;
let s = new Set();
dfs(root, root.val);
function dfs(node, tmp) {
if (tmp === sum)
ans++;
if (node.left) {
dfs(node.left, tmp + node.left.val);
if (!s.has(node.left)) {
s.add(node.left);
dfs(node.left, node.left.val);
}
}
if (node.right) {
dfs(node.right, tmp + node.right.val);
if (!s.has(node.right)) {
s.add(node.right);
dfs(node.right, node.right.val);
}
}
}
return ans;
};