Skip to content

Commit

Permalink
Trees: Binary Tree Max Path Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
phaniallamsetty committed Jan 31, 2025
1 parent 8a0c6a9 commit cbd5cca
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/main/java/com/pallamsetty/trees/BinaryTreeMaxPathSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.pallamsetty.trees;

/*
* Leetcode 124
* */

import com.pallamsetty.trees.helpers.TreeNode;

public class BinaryTreeMaxPathSum {
public int getMaxSum(TreeNode root) {
int[] res = new int[] { root.val };

dfs(root, res);
return res[0];
}

private int dfs(TreeNode root, int[] res) {
if(root == null) {
return 0;
}

int leftMax = Math.max(dfs(root.left, res), 0);
int rightMax = Math.max(dfs(root.right, res), 0);

res[0] = Math.max(res[0], root.val + leftMax + rightMax);
return root.val + Math.max(leftMax, rightMax);
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/pallamsetty/trees/BinaryTreeMaxPathSumTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.pallamsetty.trees;

import com.pallamsetty.trees.helpers.TreeNode;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class BinaryTreeMaxPathSumTest {
private final BinaryTreeMaxPathSum btmps;

public BinaryTreeMaxPathSumTest() {
btmps = new BinaryTreeMaxPathSum();
}

@Test
public void testGetMaxPathSum1() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);

assertEquals(6, btmps.getMaxSum(root));
}

@Test
public void testGetMaxPathSum2() {
TreeNode root = new TreeNode(-15);
root.left = new TreeNode(10);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.left.left = new TreeNode(-5);
root.right.right = new TreeNode(5);

assertEquals(40, btmps.getMaxSum(root));
}
}

0 comments on commit cbd5cca

Please sign in to comment.