Skip to content

Commit f6f6235

Browse files
committed
feat(113): 递归解法
1 parent eda9f5e commit f6f6235

File tree

1 file changed

+18
-20
lines changed

1 file changed

+18
-20
lines changed

Binary-Tree/113/solution1.js

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1+
/**
2+
* 时间复杂度:O(n)
3+
* 空间复杂度:O(n)
4+
*/
15
const pathSum = (root, sum) => {
2-
3-
const ans = []
4-
if (!root) {
5-
return ans
6-
}
7-
8-
order(root, sum, String(root.val))
9-
10-
return ans
6+
const ans = [];
7+
dfs(root, sum, [], ans);
118

12-
function order (root, sum, path) {
13-
if (!root) {
14-
return
15-
}
9+
return ans;
10+
}
1611

17-
if (!root.left && !root.right && sum === root.val) {
18-
ans.push(path.split(','))
19-
return
20-
}
21-
22-
root.left && order(root.left, sum - root.val, path + ',' + root.left.val)
23-
root.right && order(root.right, sum - root.val, path + ',' + root.right.val)
12+
function dfs(root, sum, path, ans) {
13+
if (!root) {
14+
return;
15+
}
2416

17+
const _sum = sum - root.val;
18+
if (!root.left && !root.right && _sum === 0) {
19+
ans.push([...path, root.val])
2520
}
21+
22+
dfs(root.left, _sum, [...path, root.val], ans);
23+
dfs(root.right, _sum, [...path, root.val], ans);
2624
}

0 commit comments

Comments
 (0)