C++ Recursive Solution


  • 0
    F

    Update the close value if the difference with the target value is lower than previous min value. Search left subtree if target value is less than root value. Otherwise, seach right subtree for close value.

     int closestValue(TreeNode* root, double target) {
            long close_value=LONG_MAX;
            double min_value=close_value;
            if(root==NULL)
             return close_value;
            if(root->left==NULL && root->right==NULL)
              return root->val;
            closestValue_BST(root,close_value,min_value,target);
            return close_value;
        }
        
        void closestValue_BST(TreeNode* root, long& close_value,double& min_value, double target)
        {
            if(root==NULL)
             return;
            if(abs(root->val-target) < min_value){
              close_value=root->val;
              min_value=abs(root->val-target);
            }
            if(root->val>target)  
                closestValue_BST(root->left,close_value, min_value, target);
            else
                closestValue_BST(root->right,close_value,min_value, target);
    
        }
    

Log in to reply
 

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