File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments