-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_0530.cpp
More file actions
52 lines (46 loc) · 1.17 KB
/
lc_0530.cpp
File metadata and controls
52 lines (46 loc) · 1.17 KB
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
/**
* @file lc_0530.cpp
* @brief https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
* @author YongDu
* @date 2021-10-03
*/
//===----------------------------- 迭代版 ------------------------------===//
class Solution {
public:
int getMinimumDifference(TreeNode *root) {
TreeNode *preNode = nullptr;
int minDiff = INT_MAX;
std::function<void(TreeNode *)> traversal = [&](TreeNode *root) {
if (root == nullptr) {
return;
}
traversal(root->left);
if (preNode) {
minDiff = std::min(root->val - preNode->val, minDiff);
}
preNode = root;
traversal(root->right);
};
traversal(root);
return minDiff;
}
};
//===----------------------------- 递归版 ------------------------------===//
class Solution {
public:
int getMinimumDifference(TreeNode *root) {
if (root == nullptr) {
return 0;
}
getMinimumDifference(root->left);
if (preNode) {
minDiff = std::min(root->val - preNode->val, minDiff);
}
preNode = root;
getMinimumDifference(root->right);
return minDiff;
}
private:
int minDiff = INT_MAX;
TreeNode *preNode = nullptr;
};