Complete the code to define the TreeNode struct with optional children.
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode {
val,
left: [1],
right: None,
}
}
}The left child is initially empty, so we use None to indicate no child.
Complete the code to calculate the maximum path sum including the current node and one child.
fn max_gain(node: &Option<Box<TreeNode>>, max_sum: &mut i32) -> i32 {
if let Some(n) = node {
let left_gain = max_gain(&n.left, max_sum).max(0);
let right_gain = max_gain(&n.right, max_sum).max(0);
let price_newpath = n.val + left_gain + right_gain;
*max_sum = (*max_sum).max(price_newpath);
return n.val + [1].max([2]);
}
0
}We return the node's value plus the maximum gain from either left or right child to continue the path upwards.
Fix the error in the recursive call to handle the right child correctly.
fn max_gain(node: &Option<Box<TreeNode>>, max_sum: &mut i32) -> i32 {
if let Some(n) = node {
let left_gain = max_gain(&n.left, max_sum).max(0);
let right_gain = max_gain(&[1], max_sum).max(0);
let price_newpath = n.val + left_gain + right_gain;
*max_sum = (*max_sum).max(price_newpath);
return n.val + left_gain.max(right_gain);
}
0
}node.right causes errors because node is an Option.n.left instead of right child.The right child is accessed via n.right inside the Some(n) block.
Fill both blanks to complete the main function that initializes max_sum and calls max_gain.
fn max_path_sum(root: Option<Box<TreeNode>>) -> i32 {
let mut max_sum = [1];
max_gain(&root, &mut max_sum);
[2]
}Initialize max_sum with the smallest integer to handle negative values, then return max_sum after computation.
Fill all three blanks to complete the recursive function that updates max_sum and returns the max gain.
fn max_gain(node: &Option<Box<TreeNode>>, max_sum: &mut i32) -> i32 {
if let Some(n) = node {
let left_gain = max_gain(&n.left, max_sum).max([1]);
let right_gain = max_gain(&n.right, max_sum).max([2]);
let price_newpath = n.val + left_gain + right_gain;
*max_sum = (*max_sum).max([3]);
return n.val + left_gain.max(right_gain);
}
0
}We ignore negative gains by comparing with 0, and update max_sum with the new path price.
