Skip to content

Instantly share code, notes, and snippets.

@lysender
Created October 6, 2023 04:00
Show Gist options
  • Save lysender/27a5455626c613c2aa76700375c04e37 to your computer and use it in GitHub Desktop.
Save lysender/27a5455626c613c2aa76700375c04e37 to your computer and use it in GitHub Desktop.
Rust - Leetcode - Easy - Sum of left leaves
// Leetcode problem: https://leetcode.com/problems/sum-of-left-leaves/
// Easy but difficult when Rust's Rc<RefCell<T>> is used for rust beginners
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn sum_of_left_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn inner_sum(node: Option<Rc<RefCell<TreeNode>>>, is_left: bool) -> i32 {
let mut sum: i32 = 0;
if let Some(node_val) = node {
let inner_node = node_val.borrow();
if inner_node.left.is_none() && inner_node.right.is_none() {
if is_left {
sum += inner_node.val;
}
}
if let Some(left) = &inner_node.left {
sum += inner_sum(Some(left.clone()), true);
}
if let Some(right) = &inner_node.right {
sum += inner_sum(Some(right.clone()), false);
}
}
sum
}
inner_sum(root, false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment