Find closest value in Binary Search Tree in C++

偶尔善良 提交于 2019-12-12 06:36:29

问题


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;
}

来源:https://stackoverflow.com/questions/43729137/find-closest-value-in-binary-search-tree-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!