forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum.java
More file actions
37 lines (36 loc) · 1.01 KB
/
BinaryTreeMaximumPathSum.java
File metadata and controls
37 lines (36 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//Back Tracking max, Recursion with return value of sum, O(N)
public class Solution {
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
int[] max = new int[1];
max[0] = Integer.MIN_VALUE;
maxPathSum(root, max);
return max[0];
}
public int maxPathSum(TreeNode node, int[] max){
if(node != null){
int left = maxPathSum(node.left, max);
int right = maxPathSum(node.right, max);
int sum = left + right + node.val;
if(sum > max[0])
max[0] = sum;
sum -= Math.min(left, right);
if(sum > 0)
return sum;
else
return 0;
}
else
return 0;
}
}