-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path530-Minimum Absolute Difference in BST.cpp
64 lines (60 loc) · 1.35 KB
/
530-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
//inorder非递归
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
if(!root)
return 0;
stack<TreeNode*>s;
int ret=INT_MAX;
int flag=0;
TreeNode *pre;
while(root||!s.empty())
{
while(root)
{
s.push(root);
root=root->left;
}
if(!s.empty())
{
root=s.top();
s.pop();
if(flag)
{
if(root->val-pre->val<ret)
ret=root->val-pre->val;
}
pre=root;
flag++;
root=root->right;
}
}
return ret;
}
};
//inorder
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
long mindiff=INT_MAX;
TreeNode *prev=nullptr;
find(root,prev,mindiff);
return mindiff;
}
void find(TreeNode *node,TreeNode*&prev,long &mindiff)
{
if(node->left)
{
find(node->left,prev,mindiff);
}
if(prev!=nullptr)
{
mindiff=min(mindiff,(long)abs(node->val-prev->val));
}
prev=node;
if(node->right)
{
find(node->right,prev,mindiff);
}
}
};