File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -224,6 +224,7 @@ mod q423;
224224mod q424;
225225mod q434;
226226mod q435;
227+ mod q437;
227228mod q441;
228229mod q442;
229230mod q443;
Original file line number Diff line number Diff line change 1+ use std:: cell:: RefCell ;
2+ use std:: rc:: Rc ;
3+
4+ use crate :: q:: Solution ;
5+
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+ #[ allow( unused) ]
14+ impl TreeNode {
15+ #[ inline]
16+ pub fn new ( val : i32 ) -> Self {
17+ TreeNode {
18+ val,
19+ left : None ,
20+ right : None ,
21+ }
22+ }
23+ }
24+
25+ #[ allow( unused) ]
26+ impl Solution {
27+ pub fn path_sum ( root : Option < Rc < RefCell < TreeNode > > > , target_sum : i32 ) -> i32 {
28+ // 方法1
29+ // dfs
30+ // 每次向下我们都将结果增加1位,然后遍历,如果结果正好等于target,就叠加计数
31+ // AC 0ms 2.2mb 126/126
32+ fn dfs ( node : Option < Rc < RefCell < TreeNode > > > , target : i32 , path : & mut Vec < i32 > ) -> i32 {
33+ if let Some ( node) = node {
34+ let left = node. borrow_mut ( ) . left . take ( ) ;
35+ let right = node. borrow_mut ( ) . right . take ( ) ;
36+ let val = node. borrow ( ) . val ;
37+ path. iter_mut ( ) . for_each ( |x| * x += val) ;
38+ path. push ( val) ;
39+ let count = path. iter ( ) . filter ( |& & x| x == target) . count ( ) as i32 ;
40+
41+ let left_count = dfs ( left, target, path) ;
42+ let right_count = dfs ( right, target, path) ;
43+
44+ path. pop ( ) ;
45+ path. iter_mut ( ) . for_each ( |x| * x -= val) ;
46+ return left_count + right_count + count;
47+ }
48+ 0
49+ }
50+ dfs ( root, target_sum, & mut Vec :: new ( ) )
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments