题目:
用 DFS,最大值应该是某一个结点左子树的最大贡献值+右子树的最大贡献值+当前结点的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| struct Solution; #[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::cell::RefCell; use std::cmp::max; use std::rc::Rc;
impl Solution { pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let mut max_sum = i32::MIN; Self::dfs(&root, &mut max_sum); max_sum } fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, max_sum: &mut i32) -> i32 { if let Some(n) = node { let n = n.borrow();
let left_gain = max(Self::dfs(&n.left, max_sum), 0); let right_gain = max(Self::dfs(&n.right, max_sum), 0);
let current_path_sum = n.val + left_gain + right_gain;
*max_sum = max(*max_sum, current_path_sum);
return n.val + max(left_gain, right_gain); } 0 } }
fn main() { println!("Hello, world!"); }
|