Readable C++ solution


  • 0
    O
    int closestValue(TreeNode* root, double target) 
      {
          return SearchValue(root, target, root->val);
      }
    
      int SearchValue(TreeNode* root, double target, int previousClosestValue)
      {
          double differenceWithPrevious = abs(target - previousClosestValue);
          double currentDifference = abs(target - root->val);
          
          int closestValueSoFar = differenceWithPrevious <= currentDifference ? previousClosestValue : root->val;
          
          if(root->val >= target && root->left != nullptr)
             return SearchValue(root->left, target, closestValueSoFar);
          else if(root->val < target && root->right != nullptr)
             return SearchValue(root->right, target, closestValueSoFar);
          
          return closestValueSoFar;
      }
    

Log in to reply
 

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