您的位置:首页 > 产品设计 > UI/UE

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

2017-07-06 11:45 417 查看
题目

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.
思路

对于这种题目,比拼的就是如何把代码写的简短,优雅和bug free了。自己原来的思路是对的,但是写出来的代码总是很长。下面给出了网上同样的思路实现的精简思路。我们知道如果target比root的值大,那么最近的值只可能在root和root的右子树上的最小值之间选择了,所以可以利用递归找出右子树上的最近值,并且最后和root的值相比较,返回更接近的值。target比root值小的情况可以对称处理。

代码

/**
 * 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 val = LONG_MAX;
        if (root->val < target && root->right) {
            val = closestValue(root->right, target);
        }
        else if (root->val > target && root->left) {
            val = closestValue(root->left, target);
        }
        if (abs(val - target) < abs(root->val - target)) {
            return val;
        }
        else {
            return root->val;
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: