c++ solution


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int result=INT_MAX;
        
        int closestValue(TreeNode* root, double target) {
            if(result==INT_MAX) result=root->val;
            result= fabs(result-target)<fabs(root->val-target) ? result:root->val;
            
            if(root->val>target){
                if(!root->left) return result;
                else 
                    return closestValue(root->left,target);
            }
            else{
                if(!root->right) return result;
                else 
                    return closestValue(root->right,target);
            }
            
        }
    };
    

Log in to reply
 

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