124. 二叉树中的最大路径和

This commit is contained in:
2026-08-13 17:38:13 +08:00
parent 5818811a53
commit 1c46d51b5f
2 changed files with 32 additions and 14 deletions
+19 -13
View File
@@ -1,24 +1,30 @@
mod arr;
mod tree;
use crate::tree::{TreeNode, build_tree_from_str};
struct Solution {}
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1];
let text1 = text1.chars().collect::<Vec<char>>();
let text2 = text2.chars().collect::<Vec<char>>();
for i in 0..text1.len() {
for j in 0..text2.len() {
dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]);
if text1[i] == text2[j] {
dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 1);
}
}
pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let (_,ans) = Self::dfs(&root);
ans
}
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
if root.is_none() {
return (-100000000, -100000000);
}
dp[text1.len()][text2.len()]
let (la, ln) = Self::dfs(&root.as_ref().unwrap().borrow().left);
let (ra, rn) = Self::dfs(&root.as_ref().unwrap().borrow().right);
let val = root.as_ref().unwrap().borrow().val;
let a = val.max(val + la).max(val + ra);
let n = a.max(ln).max(rn).max(val + la + ra);
(a, n)
}
}
fn main() {
println!(
"{:?}",
Solution::longest_common_subsequence("abcde".to_string(), "ace".to_string())
Solution::max_path_sum(build_tree_from_str("[5,4,8,11,null,13,4,7,2,null,null,null,1]"))
);
}
+13 -1
View File
@@ -15,7 +15,19 @@ impl TreeNode {
TreeNode { val, left: None, right: None }
}
}
pub fn build_tree_from_str(s: &str) -> Option<Rc<RefCell<TreeNode>>> {
// [-10,9,20,null,null,15,7]
let s = s.trim_matches(&['[', ']'][..]).split(',').map(|x| x.trim()).collect::<Vec<_>>();
let mut vals = vec![];
for x in s {
if x == "null" {
vals.push(None);
}else {
vals.push(Some(i32::from_str_radix(x, 10).unwrap()));
}
}
build_tree(&vals)
}
pub fn build_tree(vals: &[Option<i32>]) -> Option<Rc<RefCell<TreeNode>>> {
if vals.is_empty() || vals[0].is_none() {
return None;