Find closest value in Binary Search Tree in C++

2019-08-20 01:55发布

问题:

This is my code. When I run my closestValue() method, I always get 0. Does anyone know how to get the closest value to an integer? This means I want the closest integer to the one I choose the closest value to but has to be present in the tree to be displayed

 template<typename T>
T bst<T>::closestValue(T value) const {

}

template<typename T>
T bst<T>::closestValue(T value, T & closest, bst_node<T>* node) const
{
    bst<T>* pClosest = NULL;
    int minDistance = 5000;

    bst<T>* pNode = root;

    while(pNode != NULL)
    {
        int distance = abs(pNode->value - value);
        if(distance < minDistance)
        {
            minDistance = distance;
            pClosest = pNode;
        }

        if(distance == 0)
            break;

        if(pNode->m_nValue > value)
            pNode = pNode->m_pLeft;
        else if(pNode->m_nValue < value)
            pNode = pNode->m_pRight;
    }

    return pClosest;
}