Redian新闻
>
麻烦谁贴一个bug free的BST next node
avatar
麻烦谁贴一个bug free的BST next node# JobHunting - 待字闺中
w*x
1
输入是一个node*, 如果是node*那么不能仅仅根据值来搜索这个节点, 因为不同的节点
可以对应同一个值, 最差还是得搜索n次
avatar
w*x
2
输入是一个node*, 如果是node*那么不能仅仅根据值来搜索这个节点, 因为不同的节点
可以对应同一个值, 最差还是得搜索n次
avatar
a*8
3
有parent pointer吗?
avatar
z*8
4
考虑duplicate值就太没意思了

【在 w****x 的大作中提到】
: 输入是一个node*, 如果是node*那么不能仅仅根据值来搜索这个节点, 因为不同的节点
: 可以对应同一个值, 最差还是得搜索n次

avatar
H*r
5
search (*node+1) ?

【在 w****x 的大作中提到】
: 输入是一个node*, 如果是node*那么不能仅仅根据值来搜索这个节点, 因为不同的节点
: 可以对应同一个值, 最差还是得搜索n次

avatar
m*g
6
public static Node successorInBST(Node root, int key)
{
Node pos = findInBST(root, key);

if(pos == null)
{
throw new IllegalArgumentException("Cannot find the key in the
BST");
}

if(pos.getRight() != null)
{
return findSmallest(pos.getRight());
}

Node successor = null;

while(root != null)
{
if(key < root.getKey())
{
successor = root;
root = root.getLeft();
}
else if(key > root.getKey())
{
root = root.getRight();
}
else
{
break;
}
}

return successor;
}

private static Node findSmallest(Node root)
{
Validate.notNull(root, "root cannot be null");

while(root.getLeft() != null)
{
root = root.getLeft();
}

return root;
}

private static Node findInBST(Node root, int key)
{
Node p = root;

while(p != null)
{
if(p.getKey() == key)
{
return p;
}
else if(p.getKey() > key)
{
p = p.getLeft();
}
else
{
p = p.getRight();
}
}

return null;
}
avatar
m*g
7
编译过,但是没运行过。
let me know, if you find any bugs.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。