-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
36 lines (30 loc) · 922 Bytes
/
Copy pathsolution.java
File metadata and controls
36 lines (30 loc) · 922 Bytes
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
/*
class Node{
int data;
Node left, right;
Node(int d){
data=d;
left=right=null;
}
}
*/
class Solution {
private int globalMax;
// dfs returns max downward-sum from node to its parent
private int dfs(Node node) {
if (node == null) return 0;
int left = Math.max(0, dfs(node.left)); // ignore negative left contributions
int right = Math.max(0, dfs(node.right)); // ignore negative right contributions
// best path that passes through this node
int current = node.data + left + right;
globalMax = Math.max(globalMax, current);
// return best single path to parent
return node.data + Math.max(left, right);
}
int findMaxSum(Node root) {
if (root == null) return 0;
globalMax = Integer.MIN_VALUE;
dfs(root);
return globalMax;
}
}