|
@@ -0,0 +1,43 @@
|
|
|
|
+struct Solution;
|
|
|
|
+use crate::solutions::TreeNode;
|
|
|
|
+
|
|
|
|
+use std::rc::Rc;
|
|
|
|
+use std::cell::RefCell;
|
|
|
|
+
|
|
|
|
+impl Solution {
|
|
|
|
+ pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
|
|
|
+ let mut res = i32::MIN;
|
|
|
|
+ Solution::helper(root, &mut res);
|
|
|
|
+ res
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ fn helper(root: Option<Rc<RefCell<TreeNode>>>, res: &mut i32) -> i32 {
|
|
|
|
+ if let Some(node) = root {
|
|
|
|
+ let left = Solution::helper(node.borrow().left.clone(), res);
|
|
|
|
+ let right = Solution::helper(node.borrow().right.clone(), res);
|
|
|
|
+ let val = node.borrow().val;
|
|
|
|
+ let cur = val + left.max(0) + right.max(0);
|
|
|
|
+ *res = (*res).max(cur);
|
|
|
|
+
|
|
|
|
+ (val + left.max(0)).max(val + right.max(0))
|
|
|
|
+ } else {
|
|
|
|
+ 0
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod tests {
|
|
|
|
+ use super::*;
|
|
|
|
+ use crate::solutions::{vec_to_tree};
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_max_path_sum() {
|
|
|
|
+ let nums = vec![Some(-10),Some(9),Some(20),None,None,Some(15),Some(7)];
|
|
|
|
+ let root = vec_to_tree(nums);
|
|
|
|
+ let res = Solution::max_path_sum(root);
|
|
|
|
+ assert_eq!(res, 42);
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+}
|