Browse Source

feat: binary_tree_maximum_path_sum

Zhang Li 1 year ago
parent
commit
544750c3be
2 changed files with 44 additions and 0 deletions
  1. 43 0
      src/solutions/tree/binary_tree_maximum_path_sum.rs
  2. 1 0
      src/solutions/tree/mod.rs

+ 43 - 0
src/solutions/tree/binary_tree_maximum_path_sum.rs

@@ -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);
+
+    }
+}

+ 1 - 0
src/solutions/tree/mod.rs

@@ -14,3 +14,4 @@ mod balanced_binary_tree;
 mod minimum_depth_of_binary_tree;
 mod path_sum;
 mod path_sum2;
+mod binary_tree_maximum_path_sum;