Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/leetcode/algorithm_129/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Sum Root to Leaf Numbers
========================
[leetcode](https://leetcode.com/problems/sum-root-to-leaf-numbers)
36 changes: 36 additions & 0 deletions src/leetcode/algorithm_129/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub struct Solution;

use std::cell::RefCell;
use std::rc::Rc;

use super::common::TreeNode;
impl Solution {
pub fn dfs_collect(root: Option<Rc<RefCell<TreeNode>>>, mut prefix: Vec<i32>) -> Vec<Vec<i32>> {
match root {
Some(root) => {
prefix.push(root.borrow().val);
if root.borrow().right.is_none() && root.borrow().left.is_none() {
return vec![prefix];
}
let mut left = Self::dfs_collect(root.borrow().left.clone(), prefix.clone());
let mut right = Self::dfs_collect(root.borrow().right.clone(), prefix);
left.append(&mut right);
left
}
None => vec![],
}
}
pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let numbers = Self::dfs_collect(root, vec![]);
numbers
.into_iter()
.flat_map(|digits| {
digits
.into_iter()
.rev()
.enumerate()
.map(|(i, n)| n * 10_i32.pow(i as u32))
})
.sum::<i32>()
}
}
3 changes: 2 additions & 1 deletion src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod algorithm_12;
pub mod algorithm_1217;
pub mod algorithm_124;
pub mod algorithm_125;
pub mod algorithm_129;
pub mod algorithm_1345;
pub mod algorithm_1413;
pub mod algorithm_1470;
Expand All @@ -23,6 +24,7 @@ pub mod algorithm_198;
pub mod algorithm_200;
pub mod algorithm_206;
pub mod algorithm_2187;
pub mod algorithm_23;
pub mod algorithm_2306;
pub mod algorithm_238;
pub mod algorithm_2444;
Expand Down Expand Up @@ -87,4 +89,3 @@ pub mod unique_binary_search_tree_96;
pub mod valid_mountain_array_941;
pub mod valid_parentheses_20;
pub mod wiggle_subsequence_376;
pub mod algorithm_23;