Minimum Absolute Difference in BST

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.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};

vector<intv;
void dfs(TreeNode *root)
{
    if (root == NULL)
        return;
    dfs(root->left);
    v.push_back(root->data);
    dfs(root->right);
}
int getMinimumDifference(TreeNode *root)
{
    int minimumDiff = INT_MAX;
    v.clear();
    dfs(root);
    for (int i = 1i < v.size(); i++)
    {
        minimumDiff = min(minimumDiffv[i] - v[i - 1]);
    }
    return minimumDiff;
}

int main()
{
    TreeNode *root = new TreeNode(1);
    root->right = new TreeNode(3);
    root->right->left = new TreeNode(2);

    cout << getMinimumDifference(root);

    return 0;
}


No comments:

Post a Comment