Skip to content

Commit a78e079

Browse files
committed
add: Path Sum III
1 parent e1ffdd9 commit a78e079

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

β€Ž0437-path-sum-iii.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
mod tree;
2+
use tree::*;
3+
struct Solution;
4+
5+
use std::cell::RefCell;
6+
use std::rc::Rc;
7+
8+
impl Solution {
9+
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> i32 {
10+
if let Some(ref r) = root {
11+
Self::path_sum_from(root.clone(), sum)
12+
+ Self::path_sum(r.borrow().left.clone(), sum)
13+
+ Self::path_sum(r.borrow().right.clone(), sum)
14+
} else {
15+
0
16+
}
17+
}
18+
19+
fn path_sum_from(root: Option<Rc<RefCell<TreeNode>>>, remaining_sum: i32) -> i32 {
20+
if let Some(ref node) = root {
21+
let val = node.borrow().val;
22+
let path_count = if val == remaining_sum { 1 } else { 0 };
23+
path_count
24+
+ Self::path_sum_from(node.borrow().left.clone(), remaining_sum - val)
25+
+ Self::path_sum_from(node.borrow().right.clone(), remaining_sum - val)
26+
} else {
27+
0
28+
}
29+
}
30+
}
31+
32+
fn main() {
33+
assert_eq!(
34+
3,
35+
Solution::path_sum(tree![10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], 8)
36+
);
37+
assert_eq!(
38+
2,
39+
Solution::path_sum(tree![1, null, 2, null, 3, null, 4, null, 5], 3)
40+
);
41+
}

0 commit comments

Comments
 (0)