Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Max Path Sum Tree Solution
  • Loading branch information
cjae committed Apr 4, 2022
commit a67ea1dfd5fea98cbeddded6594bb46ca3a70ee7
41 changes: 41 additions & 0 deletions java/124-Binary-Tree-Maximum-Path-Sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

int[] res = new int[1];

public int maxPathSum(TreeNode root) {
res[0] = root.val;
dfs(root);
return res[0];
}

private int dfs(TreeNode node) {
if (node == null) return 0;

int leftMax = dfs(node.left);
int rightMax = dfs(node.right);

leftMax = Math.max(leftMax, 0);
rightMax = Math.max(rightMax, 0);

int allMax = leftMax + rightMax + node.val;
res[0] = Math.max(res[0], allMax);


return node.val + Math.max(leftMax, rightMax);
}
}