use std::rc::Rc; use std::cell::RefCell; #[derive(Debug)] struct TreeNode { val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { fn new(val: i32) -> Rc<RefCell<TreeNode>> { Rc::new(RefCell::new(TreeNode { val, left: None, right: None })) } } fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { fn helper(node: Option<Rc<RefCell<TreeNode>>>, max_sum: &mut i32) -> i32 { if let Some(n) = node { let left = helper(n.borrow().left.clone(), max_sum).max(0); let right = helper(n.borrow().right.clone(), max_sum).max(0); let current = n.borrow().val + left + right; *max_sum = (*max_sum).max(current); n.borrow().val + left.max(right) } else { 0 } } let mut max_sum = i32::MIN; helper(root, &mut max_sum); max_sum } fn main() { let root = TreeNode::new(-10); root.borrow_mut().left = Some(TreeNode::new(9)); let right = TreeNode::new(20); right.borrow_mut().left = Some(TreeNode::new(15)); right.borrow_mut().right = Some(TreeNode::new(7)); root.borrow_mut().right = Some(right); println!("{}", max_path_sum(Some(root))); }
The maximum path sum is 42, coming from the path 15 -> 20 -> 7, plus the root's value -10 is not included in the max path because it reduces the sum. The path 15 + 20 + 7 = 42 is the highest sum.
We use max(0, left_gain) and max(0, right_gain) to ignore any negative sums from subtrees because including a negative sum would reduce the overall path sum. This way, we only add positive contributions to the path.
fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn helper(node: Option<Rc<RefCell<TreeNode>>>, max_sum: &mut i32) -> i32 {
if let Some(n) = node {
let left = helper(n.borrow().left.clone(), max_sum);
let right = helper(n.borrow().right.clone(), max_sum);
let current = n.borrow().val + left + right;
*max_sum = (*max_sum).max(current);
n.borrow().val + left.max(right)
} else {
0
}
}
let mut max_sum = i32::MIN;
helper(root, &mut max_sum);
max_sum
}The code does not ignore negative gains from left or right subtrees, so it may include negative sums that reduce the maximum path sum, leading to incorrect results.
fn helper(node: Option<Rc<RefCell<TreeNode>>>, max_sum: &mut i32) -> i32 {
if let Some(n) = node {
let left = helper(n.borrow().left.clone(), max_sum).max(0);
let right = helper(n.borrow().right.clone(), max_sum).max(0);
let current = n.borrow().val + left + right;
*max_sum = (*max_sum).max(current);
n.borrow().val + left.max(right)
} else {
0
}
}The method call order is incorrect in option D. It attempts to call .max(0) on max_sum (&mut i32), which does not have a max method. The max(0) should be applied to the result of helper.
The maximum path sum is 10, coming from the path 1 -> 4 -> 3 -> 2 (or 2 -> 3 -> 4 -> 1). The path sum is 1 + 4 + 3 + 2 = 10. Negative nodes like -1 and -5 are excluded.
