-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath-sum-ii.js
98 lines (84 loc) · 1.93 KB
/
path-sum-ii.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Source: https://leetcode.com/problems/path-sum-ii/
* Tags: [Tree,Depth-first Search]
* Level: Medium
* Title: Path Sum II
* Auther: @imcoddy
* Content: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
*
*
* For example:
* Given the below binary tree and sum = 22,
*
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ / \
* 7 2 5 1
*
*
*
* return
*
* [
* [5,4,11,2],
* [5,8,4,5]
* ]
*/
/**
* Definition for binary tree
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @returns {number[][]}
*/
/**
* Memo: check when sum of root-to-leaf path is what we want or not. using a level to record current path index.
* Runtime: 161ms
* Rank: S
*/
var pathSum = function(root, sum) {
var result = [];
var path = [];
function hasPathSum(root, sum, level) {
if (!root) return;
path[level] = root.val;
level++;
if (!root.left && !root.right) { // check leaf
if (sum === root.val) {
var tmp = [];
for (var i = 0; i < level; i++) {
tmp.push(path[i]);
}
result.push(tmp);
}
} else { // continue DFS
hasPathSum(root.left, sum - root.val, level);
hasPathSum(root.right, sum - root.val, level);
}
}
hasPathSum(root, sum, 0);
return result;
};
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
var node = new TreeNode(1);
var root = node;
node = new TreeNode(6);
root.left = node;
node = new TreeNode(2);
root.right = node;
node = new TreeNode(4);
root.right.left = node;
node = new TreeNode(4);
root.right.right = node;
console.log(pathSum(root, 7));