3. Given the following Rust code snippet for maximum path sum in a binary tree, what is the output printed?
struct TreeNode {
val: i32,
left: Option,
right: Option,
}
fn max_gain(node: &Option, 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);
n.val + left_gain.max(right_gain)
} else {
0
}
}
fn max_path_sum(root: &Option) -> i32 {
let mut max_sum = i32::MIN;
max_gain(root, &mut max_sum);
max_sum
}
fn main() {
let root = Some(Box::new(TreeNode {
val: -10,
left: Some(Box::new(TreeNode {
val: 9,
left: None,
right: None,
})),
right: Some(Box::new(TreeNode {
val: 20,
left: Some(Box::new(TreeNode {
val: 15,
left: None,
right: None,
})),
right: Some(Box::new(TreeNode {
val: 7,
left: None,
right: None,
})),
})),
}));
println!("{}", max_path_sum(&root));
}