270. Closest Binary Search Tree Value (Easy)

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

Solution 1: Recursive 16ms

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

Solution 2: Iterative 9ms

class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        int closest = root->val;
        while (root) {
            if (abs(closest-target) > abs(root->val-target)) closest = root->val;
            root = target < root->val ? root->left:root->right;
        }
        return closest;
    }
};

results matching ""

    No results matching ""