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

Closest Binary Search Tree Value -- LeetCode

2016-08-15 02:54 405 查看
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.

思路:递归求解。因为是二叉搜索树,我们不需要遍历所有的节点,通过prune来提高速度。

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