-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinary Tree Maximum Path Sum (pyemma)
More file actions
39 lines (37 loc) · 1.02 KB
/
Binary Tree Maximum Path Sum (pyemma)
File metadata and controls
39 lines (37 loc) · 1.02 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
38
39
public class BinaryTreeMaximumPathSum {
public static int ma = Integer.MIN_VALUE;
public static int maxPathSum(TreeNode root) {
if(root == null) return 0;
maxPath(root);
return ma;
}
public static int maxPath(TreeNode root) {
if(root.left == null && root.right == null) {
ma = Math.max(ma, root.val);
return root.val;
}
else if(root.left != null && root.right == null) {
int left = maxPath(root.left);
int better = Math.max(root.val, root.val+left);
ma = Math.max(ma, better);
return better;
}
else if(root.left == null && root.right != null) {
int right = maxPath(root.right);
int better = Math.max(root.val, root.val+right);
ma = Math.max(ma, better);
return better;
}
else {
int left = maxPath(root.left);
int right = maxPath(root.right);
if(left >= 0 && right >= 0) {
ma = Math.max(ma, root.val+left+right);
}
int better = Math.max(root.val, root.val+left);
better = Math.max(better, root.val+right);
ma = Math.max(ma, better);
return better;
}
}
}