Skip to content

Commit

Permalink
added comments
Browse files Browse the repository at this point in the history
  • Loading branch information
marcomarinodev committed Apr 27, 2024
1 parent 36a0a5e commit 24d5b5e
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/problems/lec4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,28 @@ pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
}

pub fn max_sum_helper(root: &Option<Rc<RefCell<TreeNode>>>, acc: &mut i32) -> i32 {

match root {
None => 0,
Some(val) => {
let root_val = val.as_ref().borrow();

// max left path sum
let left_sum = max_sum_helper(&root_val.left, acc).max(0);

// max right path sum
let right_sum = max_sum_helper(&root_val.right, acc).max(0);

// sum of the paths
let mut total_sum = root_val.val + left_sum + right_sum;

// shall I consider the total sum in the path sum
// I have to take into account the total sum of root, left child and right child,
// as it is possible that this sum is greater than the max path sum of going
// deep donw the tree
*acc = *acc.max(&mut total_sum);

// this is the result I want to return from a subtree
// note that this does not depend on acc
root_val.val + left_sum.max(right_sum)
}
}
Expand Down

0 comments on commit 24d5b5e

Please sign in to comment.