129. 求根节点到叶节点数字之和

This commit is contained in:
2026-08-14 20:39:52 +08:00
parent d19b5d9ca8
commit 349a990512
+19 -14
View File
@@ -5,26 +5,31 @@ mod list;
mod tree;
struct Solution {}
use crate::tree::{TreeNode, build_tree_from_str};
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn maximum_length_substring(s: String) -> i32 {
let s = s.bytes().map(|x| x as usize).collect::<Vec<_>>();
let mut arr = vec![0; 'z' as usize + 1];
let mut l = 0;
let mut ans = 0;
for r in 0..s.len() {
arr[s[r]] += 1;
while arr[s[r]] > 2 {
arr[s[l]] -= 1;
l += 1;
}
ans = ans.max(r - l + 1);
pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
Self::dfs(root).iter().map(|x| x.parse::<i32>().unwrap()).sum()
}
pub fn dfs(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> {
if root.is_none() {
return vec![];
}
ans as i32
let x = root.as_ref().unwrap();
let mut arr = Self::dfs(Rc::clone(x).borrow().left.clone());
arr.append(&mut Self::dfs(Rc::clone(x).borrow().right.clone()));
if arr.is_empty() {
return vec![x.borrow().val.to_string()];
}
arr.iter().map(|y| x.borrow().val.to_string() + y).collect()
}
}
fn main() {
println!(
"{:?}",
Solution::maximum_length_substring("bcbbbcba".to_string())
Solution::sum_numbers(build_tree_from_str("[4,9,0,5,1]"))
);
}