```
class Solution {
public:
void dfs(TreeNode* root, double target, int &val)
{
val = fabs(val - target) < fabs(root->val - target) ? val : root->val;
if(root->left)
{
dfs(root->left, target, val);
}
if(root->right)
{
dfs(root->right, target, val);
}
}
int closestValue(TreeNode* root, double target) {
//special case
if(root->left == nullptr && root->right == nullptr)
{
return root->val;
}
int val = INT_MAX;
dfs(root, target, val);
return val;
}
};
```