-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeMaximumPathSum.java
58 lines (45 loc) · 1.54 KB
/
BinaryTreeMaximumPathSum.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
51
52
53
54
55
56
57
58
package techQuestions;
import com.sun.source.tree.Tree;
public class BinaryTreeMaximumPathSum {
public static 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;
}
}
static int max_sum = Integer.MIN_VALUE;
public static int max_gain(TreeNode node) {
if (node == null) return 0;
// max sum on the left and right sub-trees of node
int left_gain = Math.max(max_gain(node.left), 0);
int right_gain = Math.max(max_gain(node.right), 0);
// the price to start a new path where `node` is a highest node
int price_newpath = node.val + left_gain + right_gain;
// update max_sum if it's better to start a new path
max_sum = Math.max(max_sum, price_newpath);
// for recursion :
// return the max gain if continue the same path
return node.val + Math.max(left_gain, right_gain);
}
public static int maxPathSum(TreeNode root) {
max_gain(root);
return max_sum;
}
public static void main(String[] args) {
TreeNode tree = new TreeNode(-10);
tree.left = new TreeNode(9);
tree.right = new TreeNode(20);
tree.right.left = new TreeNode(15);
tree.right.right = new TreeNode(7);
System.out.println(maxPathSum(tree));
}
}