File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // Definition for a binary tree node.
2+ // #[derive(Debug, PartialEq, Eq)]
3+ // pub struct TreeNode {
4+ // pub val: i32,
5+ // pub left: Option<Rc<RefCell<TreeNode>>>,
6+ // pub right: Option<Rc<RefCell<TreeNode>>>,
7+ // }
8+ //
9+ // impl TreeNode {
10+ // #[inline]
11+ // pub fn new(val: i32) -> Self {
12+ // TreeNode {
13+ // val,
14+ // left: None,
15+ // right: None
16+ // }
17+ // }
18+ // }
19+ use std:: rc:: Rc ;
20+ use std:: cell:: RefCell ;
21+ #[ derive( Copy , Clone ) ]
22+ enum DIR {
23+ LEFT ,
24+ RIGHT ,
25+ }
26+ impl Solution {
27+ pub fn sum_of_left_leaves ( root : Option < Rc < RefCell < TreeNode > > > ) -> i32 {
28+ Self :: solve ( root, DIR :: RIGHT )
29+ }
30+ fn solve ( root : Option < Rc < RefCell < TreeNode > > > , dir : DIR ) -> i32 {
31+ let mut ret = 0 ;
32+ if let Some ( root) = root {
33+ let mut node = root. borrow_mut ( ) ;
34+ if node. left . is_none ( ) && node. right . is_none ( ) {
35+ // leaf node
36+ ret = match dir {
37+ DIR :: LEFT => node. val ,
38+ _ => 0 ,
39+ } ;
40+ } else {
41+ let left = Self :: solve ( node. left . take ( ) , DIR :: LEFT ) ;
42+ let right = Self :: solve ( node. right . take ( ) , DIR :: RIGHT ) ;
43+
44+
45+ ret = left + right;
46+ }
47+ }
48+ ret
49+ }
50+
51+ }
You can’t perform that action at this time.
0 commit comments