[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; } }};
阅读全文
0 0
- [leetcode] 270. Closest Binary Search Tree Value 解题报告
- [Leetcode] 270. Closest Binary Search Tree Value 解题报告
- [leetcode] 272. Closest Binary Search Tree Value II 解题报告
- [Leetcode] 272. Closest Binary Search Tree Value II 解题报告
- LeetCode 270. Closest Binary Search Tree Value
- [Leetcode]Closest Binary Search Tree Value II
- [Leetcode]Closest Binary Search Tree Value
- leetcode 270: Closest Binary Search Tree Value
- *LeetCode-Closest Binary Search Tree Value
- [leetcode 270] Closest Binary Search Tree Value
- Leetcode 270Closest Binary Search Tree Value
- LeetCode 270: Closest Binary Search Tree Value
- Leetcode 270 Closest Binary Search Tree Value
- Leetcode 270. Closest Binary Search Tree Value (cpp)
- 270. Closest Binary Search Tree Value
- 270. Closest Binary Search Tree Value
- Closest Binary Search Tree Value
- Closest Binary Search Tree Value
- SVN常见问题及其解决方法 .
- Android开发log.d级别日志不打印
- MyBatis中Like语句使用方式
- 搭建SSM框架遇到的注解
- Peewee中文文档【三】:应用实例
- [Leetcode] 270. Closest Binary Search Tree Value 解题报告
- java 猴子吃桃问题
- 访问量突破200万次
- 记录各大牛个人主页,紧密跟踪其学术动态
- 【Android多媒体(重采样与混频)】从录音流程分析AudioResampler
- 双主+haproxy手工切换的一个注意点
- 前端知识点
- 多行转多列并且分组合并列
- java.lang.OutOfMemoryError: PermGen space及其解决方法