Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 05950c7

Browse files
author
guangsheng.li01
committed
Solved a1315
1 parent 95be04b commit 05950c7

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* [1315] sum-of-nodes-with-even-valued-grandparent
3+
*/
4+
5+
use super::utils::tree::*;
6+
pub struct Solution {}
7+
8+
// solution impl starts here
9+
10+
// Definition for a binary tree node.
11+
// #[derive(Debug, PartialEq, Eq)]
12+
// pub struct TreeNode {
13+
// pub val: i32,
14+
// pub left: Option<Rc<RefCell<TreeNode>>>,
15+
// pub right: Option<Rc<RefCell<TreeNode>>>,
16+
// }
17+
//
18+
// impl TreeNode {
19+
// #[inline]
20+
// pub fn new(val: i32) -> Self {
21+
// TreeNode {
22+
// val,
23+
// left: None,
24+
// right: None
25+
// }
26+
// }
27+
// }
28+
use std::cell::RefCell;
29+
use std::rc::Rc;
30+
impl Solution {
31+
pub fn sum_even_grandparent(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
32+
let mut sum: i32 = 0;
33+
Self::dfs(1, 1, root, &mut sum);
34+
sum
35+
}
36+
37+
fn dfs(gval: i32, pval: i32, root: Option<Rc<RefCell<TreeNode>>>, sum: &mut i32) {
38+
if let Some(root) = root {
39+
let root = root.borrow();
40+
if gval % 2 == 0 {
41+
*sum += root.val;
42+
}
43+
44+
Self::dfs(pval, root.val, root.left.clone(), sum);
45+
Self::dfs(pval, root.val, root.right.clone(), sum);
46+
}
47+
}
48+
}
49+
50+
// solution impl ends here
51+
52+
// solution tests starts here
53+
54+
#[cfg(test)]
55+
mod tests {
56+
use super::*;
57+
58+
#[test]
59+
fn test_case0() {
60+
assert_eq!(
61+
Solution::sum_even_grandparent(tree![
62+
6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5
63+
]),
64+
18
65+
);
66+
}
67+
}
68+
69+
// solution tests ends here

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,5 @@ mod a1047_remove_all_adjacent_duplicates_in_string;
4747
mod a1200_minimum_absolute_difference;
4848
mod a1287_element_appearing_more_than_25_in_sorted_array;
4949
mod a1302_deepest_leaves_sum;
50+
mod a1315_sum_of_nodes_with_even_valued_grandparent;
5051
mod a1317_convert_integer_to_the_sum_of_two_no_zero_integers;

0 commit comments

Comments
 (0)