-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMinimum Absolute Difference In BST.cpp
69 lines (49 loc) · 1.25 KB
/
Minimum Absolute Difference In BST.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
// Naive Approach
class Solution
{
public:
void inorder(Node* root, vector<int>& v)
{
if(root)
{
inorder(root->left, v);
v.push_back(root->data);
inorder(root->right, v);
}
}
int absolute_diff(Node *root)
{
//Your code here
vector<int> v;
inorder(root, v);
int res = INT_MAX;
for(int i = 1; i < v.size(); ++i)
res = min(res, v[i] - v[i-1]);
return res;
}
};
// Expected Approach
class Solution
{
public:
void inorder(Node* root, Node*& prev, int& ans)
{
if(root)
{
inorder(root->left, prev, ans);
if(prev)
ans = min(ans, root->data - prev->data);
prev = root;
inorder(root->right, prev, ans);
}
}
int absolute_diff(Node *root)
{
//Your code here
// Time Complexity -> O(n)
// Space Complexity -> O(1) // O(N) auxiliary stack space
int ans = INT_MAX;
Node* prev = nullptr;
inorder(root, prev, ans);
return ans;
}