-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8a0c6a9
commit cbd5cca
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
28 changes: 28 additions & 0 deletions
28
src/main/java/com/pallamsetty/trees/BinaryTreeMaxPathSum.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
35
src/test/java/com/pallamsetty/trees/BinaryTreeMaxPathSumTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} |