C++ Recursive Solution


  • 0
    J
    class Solution {
    private: 
        int res = INT_MAX;
    public:
        int closestValue(TreeNode* root, double target) {
            if(root==NULL) return res;
            
            double cur = (double) (root->val);
            
            if(cur==target) return root->val;
            
            if(res==INT_MAX || abs(res-target)> abs(cur-target))
                res = cur;
            if(cur>target) 
                closestValue(root->left, target);
            else
                closestValue(root->right, target);
            
        }
    };

  • 2
    Y

    just one thing with the double/float comparison, using == is not recommended

    better using epsilon:

    bool doubleEqual(double a, double b){
        return abs(a-b) <= std::numeric_limits<double>::epsilon();
    }

  • 0
    J

    thank you! good comment.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.