Leetcode 270 Solution

This article provides solution to leetcode question 270 (closest-binary-search-tree-value)

https://leetcode.com/problems/closest-binary-search-tree-value

Solution

/**
 * 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) {
        TreeNode* p = root;
        int opt_val = root->val;

        while (p)
        {
            if (abs(p->val - target) < abs(opt_val - target))
                opt_val = p->val;

            if (p->val == target)
                return p->val;
            else if (p->val > target)
                p = p->left;
            else
                p = p->right;
        }

        return opt_val;
    }
};