900. 二叉搜索树中最接近的值:
给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值
给出的目标值为浮点数
我们可以保证只有唯一一个最接近给定值的节点
样例 1:
输入:
root = {5,4,9,2,#,8,10} and target = 6.124780
输出:
5
解释:
二叉树 {5,4,9,2,#,8,10},表示如下的树结构:
5
/ \
4 9
/ / \
2 8 10
样例 2:
输入:
root = {3,2,4,1} and target = 4.142857
输出:
4
解释:
二叉树 {3,2,4,1},表示如下的树结构:
3
/ \
2 4
/
1
分析
对于二叉搜索树1,如果是找相等的值,大家应该比较清楚,但是最相近的值,肯定有些摸不着头脑。其实,相等的就是最相近的,如果没有相等的,那么答案一定是比目标小的里面最大的和比目标大的里面最小的之一。
题解
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the given BST
* @param target: the given target
* @return: the value in the BST that is closest to the target
*/
public int closestValue(TreeNode root, double target) {
// write your code here
// 比目标值大的最小值
TreeNode minGtNode = null;
// 比目标值小的最大值
TreeNode maxLtNode = null;
// 遍历到的节点
TreeNode node = root;
while (node != null) {
if (node.val > target) {
if (minGtNode == null
|| node.val < minGtNode.val) {
// 赋值比目标值大的最小值
minGtNode = node;
}
node = node.left;
} else if(node.val < target) {
if (maxLtNode == null
|| node.val > maxLtNode.val) {
// 赋值比目标值小的最大值
maxLtNode = node;
}
node = node.right;
} else {
// 节点值和目标值相等
return node.val;
}
}
if (maxLtNode == null) {
return minGtNode.val;
}
if (minGtNode == null) {
return maxLtNode.val;
}
if (Math.abs(minGtNode.val - target) < Math.abs(maxLtNode.val - target)) {
return minGtNode.val;
} else {
return maxLtNode.val;
}
}
}
最后说两句
非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~
作者水平有限,如果文章内容有不准确的地方,请指正。
希望小伙伴们都能每天进步一点点。
本文由 二当家的白帽子 https://le-yi.blog.csdn.net/ 博客原创,转载请注明来源,谢谢~
百科:二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。二叉搜索树作为一种经典的数据结构,它既有链表的快速插入与删除操作的特点,又有数组快速查找的优势;所以应用十分广泛,例如在文件系统和数据库系统一般会采用这种数据结构进行高效率的排序与检索操作。 ↩︎