Skip to main content

783. Minimum Distance Between BST Nodes

Hint

/**
* 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 {
vector<int> v;
public:
int minDiffInBST(TreeNode* root)
{
dfs(root);
sort(v.begin(), v.end());
int minDiff = INT_MAX;
for (int i = 1; i < v.size(); i++)
{
minDiff = min(minDiff, v[i] - v[i - 1]);
}
return minDiff;
}
void dfs(TreeNode* root)
{
if(!root) return;
dfs(root->left);
v.push_back(root->val);
dfs(root->right);
}
};
  • T: O()O()
  • S: O()O()