-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsum_of_left_leaves.rs
More file actions
30 lines (27 loc) · 856 Bytes
/
sum_of_left_leaves.rs
File metadata and controls
30 lines (27 loc) · 856 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use super::prelude::*;
fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
helper(root, false)
}
fn helper(node: Option<Rc<RefCell<TreeNode>>>, is_left: bool) -> i32 {
match node {
Some(node) => {
let node = node.borrow();
if node.left.is_none() && node.right.is_none() {
if is_left {
return node.val;
}
return 0;
}
helper(node.left.clone(), true) + helper(node.right.clone(), false)
}
None => 0,
}
}
#[test]
fn test_sum_of_left_leaves() {
const TEST_CASES: [(&[i32], i32); 1] = [(&[3, 9, 20, null, null, 15, 7], 24)];
for (input, output) in TEST_CASES {
let input = deserialize_vec_to_binary_tree(input);
assert_eq!(sum_of_left_leaves(input), output);
}
}