4-line iterative c++ solution using minimize difference


  • 0
    A
        int closestValue(TreeNode* root, double target) {
            double diff = target - root->val;
            for( ; root ; root = target < root->val ? root->left : root->right)
                if(abs(target - root->val) < abs(diff)) diff = target - root->val;
            return target + 0.5 - diff;
        }
    

    we maintain a minimal diff. The last line to avoid the cases like 3.999999 to 3 , which key in bst is 4.


Log in to reply
 

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