Skip to content

Commit 1e01554

Browse files
committed
[feat ]: leetcode 404
Signed-off-by: Bo-Wei Chen(BWbwchen) <tim.chenbw@gmail.com>
1 parent 2c93979 commit 1e01554

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
 (0)