-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path530.minimum-absolute-difference-in-bst.cpp
67 lines (67 loc) · 1.33 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
65
66
67
/*
* @lc app=leetcode id=530 lang=cpp
*
* [530] Minimum Absolute Difference in BST
*
* https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/
*
* algorithms
* Easy (49.02%)
* Total Accepted: 49.6K
* Total Submissions: 101.1K
* Testcase Example: '[1,null,3,2]'
*
* Given a binary search tree with non-negative values, find the minimum
* absolute difference between values of any two nodes.
*
* Example:
*
*
* Input:
*
* 1
* \
* 3
* /
* 2
*
* Output:
* 1
*
* Explanation:
* The minimum absolute difference is 1, which is the difference between 2 and
* 1 (or between 2 and 3).
*
*
*
*
* Note: There are at least two nodes in this BST.
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minn = INT_MAX;
int prev = INT_MAX;
void callme(TreeNode* root){
if(root == NULL)
return;
callme(root->left);
if(prev != INT_MAX)
minn = min(minn, abs(prev - root->val));
prev = root->val;
callme(root->right);
}
int getMinimumDifference(TreeNode* root) {
callme(root);
return minn;
}
};