Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit dd21478

Browse files
committed
src/bin/path-sum-ii.rs
1 parent b1ec11b commit dd21478

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

src/bin/path-sum-ii.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
// Definition for a binary tree node.
6+
#[derive(Debug, PartialEq, Eq)]
7+
pub struct TreeNode {
8+
pub val: i32,
9+
pub left: Option<Rc<RefCell<TreeNode>>>,
10+
pub right: Option<Rc<RefCell<TreeNode>>>,
11+
}
12+
13+
impl TreeNode {
14+
#[inline]
15+
pub fn new(val: i32) -> Self {
16+
TreeNode {
17+
val,
18+
left: None,
19+
right: None,
20+
}
21+
}
22+
}
23+
24+
use std::rc::Rc;
25+
use std::cell::RefCell;
26+
27+
impl Solution {
28+
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> Vec<Vec<i32>> {
29+
match Self::f(root, target_sum) {
30+
Some(x) => x,
31+
None => vec![]
32+
}
33+
}
34+
35+
fn f(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> Option<Vec<Vec<i32>>> {
36+
if root.is_none() {
37+
return None;
38+
}
39+
40+
let value = root.as_ref().unwrap().borrow().val;
41+
let left = root.as_ref().unwrap().borrow_mut().left.take();
42+
let right = root.as_ref().unwrap().borrow_mut().right.take();
43+
44+
if target_sum - value == 0 {
45+
if left.is_none() && right.is_none() {
46+
return Some(vec![vec![value]]);
47+
}
48+
}
49+
50+
let mut left = match Self::f(left, target_sum - value) {
51+
Some(mut x) => {
52+
x.iter_mut().for_each(|x| x.insert(0, value));
53+
x
54+
}
55+
None => vec![]
56+
};
57+
58+
let mut right = match Self::f(right, target_sum - value) {
59+
Some(mut x) => {
60+
x.iter_mut().for_each(|x| x.insert(0, value));
61+
x
62+
}
63+
None => vec![]
64+
};
65+
66+
right.append(&mut left);
67+
if right.len() == 0 {
68+
None
69+
} else {
70+
Some(right)
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)