由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 想到一道老题
相关主题
麻烦谁贴一个bug free的BST next node一道在线题
amazon on-site interview请教一道g算法题
树 inorder下个节点最好办法是啥求教Leetcode题目:Lowest Common Ancestor
一道二叉树的老题BST面试题
问个google面试题求教:binary search tree中找第i大的数
请教linked list, 删除最后一个节点一个老题binary tree找 lowest common ancestor 的code (请教
插入节点到complete binary tree的末尾判断BT是否BST?
这最小公共父母节点有bug吗?find the k-th maximum node in a binary search tree 有疑问
相关话题的讨论汇总
话题: root话题: value话题: node话题: null话题: result
进入JobHunting版参与讨论
1 (共1页)
s******n
发帖数: 65
1
突然想到一个题目,找到BST中离目标最近的那个数
大家又什么好解法?
s*****y
发帖数: 897
2
I saw this question on this board 2-3 weeks ago.

【在 s******n 的大作中提到】
: 突然想到一个题目,找到BST中离目标最近的那个数
: 大家又什么好解法?

g**u
发帖数: 583
3

假设该元素不在BST中,首先找到最后一个比该元素小的节点,然后找到第一个比该元素大的节点,返回2个节点中离目标最近的节点。
下面是实现,等待拍砖。
node * findClose(node *root, int value)
{
if(!root)
return NULL;
node * smaller=findLastSmaller(root, value);
node * greater=findFirstGrearer(root, value);
//we will also need to check both of smaller and greater are not NULL
return value-smaller->value< greater->value - value?smaller:greater;
}
node * findLastSmaller(node * root, int value)
{
if(!root)
return NULL;
node * result=NULL;
while(root)
{
if(root->value >= value)
root=root->left;
else{
result=root;
root=root->right;
}
}
return result;
}
node * findFirstGreater(node * root, int value)
{
if(!root)
return NULL;
node * result=NULL;
while(root)
{
if(root->value<=value)
root=root->right;
else{
result=root;
root=root->left;
}
}
return result;
}
时间复杂度是 O(log n), 空间复杂度是O(1)
还有一个做法就是in-order visit,然后做binary search, 找到该元素的区间,然后寻找目标节点。 时间复杂度是一样的,但空间复杂度就是 O(n)了

【在 s******n 的大作中提到】
: 突然想到一个题目,找到BST中离目标最近的那个数
: 大家又什么好解法?

1 (共1页)
进入JobHunting版参与讨论
相关主题
find the k-th maximum node in a binary search tree 有疑问问个google面试题
问题在哪儿啊 kth Node of BST,大家帮忙请教linked list, 删除最后一个节点
发现一个很恶心的基础问题插入节点到complete binary tree的末尾
Find the node with given value in binary tree in in-order这最小公共父母节点有bug吗?
麻烦谁贴一个bug free的BST next node一道在线题
amazon on-site interview请教一道g算法题
树 inorder下个节点最好办法是啥求教Leetcode题目:Lowest Common Ancestor
一道二叉树的老题BST面试题
相关话题的讨论汇总
话题: root话题: value话题: node话题: null话题: result