forked from shogunsea/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-maximum-path-sum.java
52 lines (45 loc) · 1.65 KB
/
binary-tree-maximum-path-sum.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int maxPathSum(TreeNode root) {
// write your code here
// the idea is that: we want to figure out
// maximal path sum in a tree, no matter where it starts
// and ends. So for any tree node, it could form two types
// of path, one is go from left child to right child, the other is
// go from one of the child and up to its parent node.
// Both cases could form the maximal path. We update global sum
// by comparing the two. The return value should be current node value
// plus the bigger one from left or right child, which is the maximal
// value this node can contribute.
// as a pointer to result.
int[] res = {root.val};
dfsHelper(root, res);
return res[0];
}
public int dfsHelper(TreeNode node, int[] res) {
if (node == null) {
return 0;
}
int left = dfsHelper(node.left, res);
int right = dfsHelper(node.right, res);
int maxContribute = Math.max(node.val, Math.max(left + node.val, right + node.val));
int crossSum = left + right + node.val;
int localMax = Math.max(crossSum, maxContribute);
res[0] = Math.max(res[0], localMax);
return maxContribute;
}
}