blob: 0c0ef82b7cd9bdacde419c11074a690745e7a7b4 (
plain)
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
|
// 530. Minimum Absolute Difference in BST
#include "leetcode.h"
/*
* given the 'root' of a binary search tree (bst), return the minimum absolute
* difference between the values of any two different nodes in the tree
*/
class Solution {
int diff = INT_MAX;
TreeNode *prev = NULL;
void dfs(TreeNode *root) {
if (root->left)
dfs(root->left);
if (prev)
diff = min(diff, abs(prev->val - root->val));
prev = root;
if (root->right)
dfs(root->right);
}
public:
int getMinimumDifference(TreeNode *root) {
dfs(root);
return diff;
}
};
|