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

来源:互联网 发布:完美匹配算法 编辑:程序博客网 时间:2024/05/17 01:31

题目

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;        }    }};

原创粉丝点击