-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST Maximum Difference.java
50 lines (41 loc) · 1.21 KB
/
BST Maximum Difference.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
class Solution{
static int res;
public static int maxDifferenceBST(Node root,int target){
int sum=0;
Node curr=root;
while(curr!=null){
if(curr.data==target)
break;
else if(curr.data < target){
sum+= curr.data;
curr =curr.right;
}
else{
sum+=curr.data;
curr=curr.left;
}
}
if(curr==null)
return -1;
else{
if(curr.left==null && curr.right==null)
return sum;
res=Integer.MIN_VALUE;
if(curr.left!=null)
solve(curr.left, 0, sum);
if(curr.right!=null)
solve(curr.right, 0, sum);
}
return res;
}
static void solve(Node root, int path_sum , int sum){
if(root==null)
return;
if(root.left==null && root.right==null){
res=Math.max(res, sum - (path_sum+root.data));
return;
}
solve(root.left, path_sum+root.data, sum);
solve(root.right, path_sum+root.data, sum);
}
}