diff --git a/src/problem/mod.rs b/src/problem/mod.rs index de9fa75..8051d6d 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -145,4 +145,5 @@ mod p226_invert_binary_tree; mod p101_symmetric_tree; mod p114_flatten_binary_tree_to_linked_list; mod p112_path_sum; -mod p129_sum_root_to_leaf_numbers; \ No newline at end of file +mod p129_sum_root_to_leaf_numbers; +mod p124_binary_tree_maximum_path_sum; \ No newline at end of file diff --git a/src/problem/p124_binary_tree_maximum_path_sum.rs b/src/problem/p124_binary_tree_maximum_path_sum.rs new file mode 100644 index 0000000..c7c5d82 --- /dev/null +++ b/src/problem/p124_binary_tree_maximum_path_sum.rs @@ -0,0 +1,75 @@ +/** + * [124] Binary Tree Maximum Path Sum + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn max_sum(node: &Rc>, result: &mut i32) -> i32 { + if node.borrow().left.is_none() && node.borrow().right.is_none() { + *result = (*result).max(node.borrow().val); + + return node.borrow().val; + } + + let left_sum = if let Some(left) = &node.borrow().left { + Self::max_sum(left, result) + } else { + 0 + }.max(0); + + let right_sum = if let Some(right) = &node.borrow().right { + Self::max_sum(right, result) + } else { + 0 + }.max(0); + + *result = (*result).max(node.borrow().val + left_sum + right_sum); + + node.borrow().val + left_sum.max(right_sum) + } + + pub fn max_path_sum(root: Option>>) -> i32 { + let mut result = i32::MIN; + + if let Some(root) = root { + Self::max_sum(&root, &mut result); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_124() { + } +}