[LeetCode] Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
void dfs(TreeNode* node, vector<int>& vals) {
if(!node) return;
vals.push_back(node->val);
dfs(node->left, vals);
dfs(node->right, vals);
}
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
vector<int> vals;
dfs(root,vals);
sort(begin(vals), end(vals));
for(int i = 0; i < vals.size() - 1; i++) {
res = min(res, abs(vals[i] - vals[i+1]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/17/PS/LeetCode/minimum-distance-between-bst-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.