270. Closest Binary Search Tree Value

/**
 * 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 closestValue(TreeNode* root, double target) {
        auto kid = target < root->val ? root->left : root->right;
        if (!kid) return root->val;
        int closestKid = closestValue(kid, target);
        return abs(root->val - target) < abs(closestKid - target) ? root->val : closestKid;
    }
};

results matching ""

    No results matching ""