Posted on

Description

Submission

/**
 * 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 {
    void dfs(TreeNode* root, double target, int& ret) {
        if(root == NULL) return;
        if(abs(root->val - target) < abs(ret - target)) ret = root->val;
        if(target <= root->val) dfs(root->left, target, ret);
        else dfs(root->right, target, ret);
    }
public:
    int closestValue(TreeNode* root, double target) {
        int ret = root->val;

        dfs(root, target, ret);

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *