124. 二叉树中的最大路径和
This commit is contained in:
+19
-13
@@ -1,24 +1,30 @@
|
|||||||
mod arr;
|
mod arr;
|
||||||
|
mod tree;
|
||||||
|
|
||||||
|
use crate::tree::{TreeNode, build_tree_from_str};
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
|
pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||||
let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1];
|
let (_,ans) = Self::dfs(&root);
|
||||||
let text1 = text1.chars().collect::<Vec<char>>();
|
ans
|
||||||
let text2 = text2.chars().collect::<Vec<char>>();
|
}
|
||||||
for i in 0..text1.len() {
|
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
|
||||||
for j in 0..text2.len() {
|
if root.is_none() {
|
||||||
dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]);
|
return (-100000000, -100000000);
|
||||||
if text1[i] == text2[j] {
|
|
||||||
dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
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() {
|
fn main() {
|
||||||
println!(
|
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
@@ -15,7 +15,19 @@ impl TreeNode {
|
|||||||
TreeNode { val, left: None, right: None }
|
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>>> {
|
pub fn build_tree(vals: &[Option<i32>]) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
if vals.is_empty() || vals[0].is_none() {
|
if vals.is_empty() || vals[0].is_none() {
|
||||||
return None;
|
return None;
|
||||||
|
|||||||
Reference in New Issue
Block a user