Skip to content

Commit f7df505

Browse files
committed
feat: optimize solutions to lcof problem: No.13
面试题34. 二叉树中和为某一值的路径
1 parent 5bfd9c5 commit f7df505

File tree

2 files changed

+20
-23
lines changed

2 files changed

+20
-23
lines changed

lcof/面试题34. 二叉树中和为某一值的路径/Solution.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,44 +16,42 @@
1616
// }
1717
// }
1818
// }
19-
use std::cell::RefCell;
2019
use std::rc::Rc;
20+
use std::cell::RefCell;
2121

2222
impl Solution {
23-
fn dfs(
24-
root: &Option<Rc<RefCell<TreeNode>>>,
25-
mut target: i32,
26-
mut values: Vec<i32>,
27-
) -> Vec<Vec<i32>> {
23+
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, mut target: i32, paths: &mut Vec<i32>) -> Vec<Vec<i32>> {
2824
let node = root.as_ref().unwrap().borrow();
29-
values.push(node.val);
25+
paths.push(node.val);
3026
target -= node.val;
3127
let mut res = vec![];
3228
// 确定叶结点身份
3329
if node.left.is_none() && node.right.is_none() {
3430
if target == 0 {
35-
res.push(values);
31+
res.push(paths.clone());
3632
}
33+
paths.pop();
3734
return res;
3835
}
3936
if node.left.is_some() {
40-
let res_l = Solution::dfs(&node.left, target, values.clone());
37+
let res_l = Solution::dfs(&node.left, target, paths);
4138
if !res_l.is_empty() {
4239
res = [res, res_l].concat();
4340
}
4441
}
4542
if node.right.is_some() {
46-
let res_r = Solution::dfs(&node.right, target, values.clone());
43+
let res_r = Solution::dfs(&node.right, target, paths);
4744
if !res_r.is_empty() {
4845
res = [res, res_r].concat();
4946
}
5047
}
48+
paths.pop();
5149
res
5250
}
5351
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target: i32) -> Vec<Vec<i32>> {
5452
if root.is_none() {
5553
return vec![];
5654
}
57-
Solution::dfs(&root, target, vec![])
55+
Solution::dfs(&root, target, &mut vec![])
5856
}
59-
}
57+
}

lcof/面试题34. 二叉树中和为某一值的路径/Solution.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,25 @@
1313
*/
1414

1515
function pathSum(root: TreeNode | null, target: number): number[][] {
16-
const res = [];
16+
const res: number[][] = [];
1717
if (root == null) {
1818
return res;
1919
}
20-
const dfs = (
21-
{ val, right, left }: TreeNode,
22-
target: number,
23-
values: number[]
24-
) => {
25-
values.push(val);
20+
const paths: number[] = [];
21+
const dfs = ({ val, right, left }: TreeNode, target: number) => {
22+
paths.push(val);
2623
target -= val;
2724
if (left == null && right == null) {
2825
if (target === 0) {
29-
res.push(values);
26+
res.push([...paths]);
3027
}
28+
paths.pop();
3129
return;
3230
}
33-
left && dfs(left, target, [...values]);
34-
right && dfs(right, target, [...values]);
31+
left && dfs(left, target);
32+
right && dfs(right, target);
33+
paths.pop();
3534
};
36-
dfs(root, target, []);
35+
dfs(root, target);
3736
return res;
3837
}

0 commit comments

Comments
 (0)