[leetcode] 270. Closest Binary Search Tree Value 解题报告

题目链接:https://leetcode.com/problems/closest-binary-search-tree-value/

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.

思路:搜索二叉树的特性就是左孩子肯定比根小,右孩子肯定比根大.因此在搜索的时候如果碰到一个值比target大的结点,说明这个结点的右边肯定比target更大,因此只需要向左孩子找,直到叶子结点.这样就可以找到一个最靠近的值.需要注意的整型溢出问题.

代码如下:

/**
 * 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) {
        long ans = root->val, val = LONG_MAX;
        if(target > ans && root->right)
            val = closestValue(root->right, target);
        else if(target <= ans && root->left)
            val = closestValue(root->left, target);
        if(fabs(val-target) < fabs(ans-target)) ans = val;
        return ans;
    }
};


你可能感兴趣的:(leetcode,binary,tree,binary,search,tree)