Trees and Graphs‎ > ‎

Find Closest Binary Search Tree Element

Given a value n and a BST, return a value stored in the BST that is closest to n.

int FindClosestElement(Node *root, int n)
{
    if (!root)
        throw("Bad input!");
 
    int ret = root->value;
    Node *curr = root;
    while (nullptr != curr)
    {
        if (n == curr->value)
            return n;
        if (abs(n - curr->value) < abs(n - ret))
            ret = curr->value;
 
        if (n < curr->value)
            curr = curr->left;
        else
            curr = curr->right;
    }
 
    return ret;
}
Comments