-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST Maximum Difference.cpp
88 lines (75 loc) · 1.71 KB
/
BST Maximum Difference.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
#define MAX_HEIGHT 100000
// Tree Node
struct Node {
int data;
Node *right;
Node *left;
Node(int x) {
data = x;
right = NULL;
left = NULL;
}
};
Node *insert(Node *tree, int val) {
Node *temp = NULL;
if (tree == NULL) return new Node(val);
if (val < tree->data) {
tree->left = insert(tree->left, val);
} else if (val > tree->data) {
tree->right = insert(tree->right, val);
}
return tree;
}
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
int ans=-1e9-7;
int solve(Node *root,int t,int path){
if(root==NULL)return 0;
if(root->left==NULL&&root->right==NULL){
if(root->data==t)ans=max(ans,path);
return root->data;
}
int tmp=1e9+7;
if(root->left)tmp=min(tmp,solve(root->left,t,path+root->data));
if(root->right)tmp=min(tmp,solve(root->right,t,path+root->data));
if(root->data==t)ans=max(ans,path-tmp);
return root->data+tmp;
}
int maxDifferenceBST(Node *root,int t){
solve(root,t,0);
if(ans<=-1e9-7)return -1;
return ans;
}
};
// 8
// 20
// 15 19
// 9 17 20
// }; 10
//{ Driver Code Starts.
int main() {
int T;
cin >> T;
while (T--) {
Node *root = NULL;
int N;
cin >> N;
for (int i = 0; i < N; i++) {
int k;
cin >> k;
root = insert(root, k);
}
int target;
cin >> target;
Solution ob;
cout << ob.maxDifferenceBST(root, target);
cout << endl;
}
}
// } Driver Code Ends