【发布时间】:2015-07-04 23:06:21
【问题描述】:
BST 中元素的后继者是该元素在 BST 中的后继者 由中序遍历确定的排序顺序。寻找 当每个节点都有一个指向其父节点的指针时出现后继 在 CLRS 的算法教科书中(麻省理工学院的算法简介 按)。
如果结构中没有parent,有没有办法找到大于 X 的第一个值?喜欢:
typedef struct tree tree;
struct tree{
int value;
tree *left;
tree *right;
};
//Function:
tree *find_first_bigger(tree *t, int x){}
我尝试过使用:
tree *find_first_bigger(tree *t, int x){
if(t == NULL)
return NULL;
if((*t)->value > x)
find_first_bigger((*t)->left, x);
else if((*t)->value < x)
find_first_bigger((*t)->right), x);
else if((*t)->value == x){
if((*t)->right != NULL)
return tree_first_bigger((*t)->right);
else
return tree;
}
}
在这个例子中(它使用字母,但没有问题),如果我尝试搜索大于N的第一个(它应该返回我O)但它返回我N。
【问题讨论】:
-
我认为您应该为该递归函数放置基本情况(如果当前节点为空),以便在树中没有比 X 更大的键时停止。您还应该检查是否找到了密钥并将其归还。
-
@PlayHardGoPro 不要担心被否决,我的解决方案是 100% 正确的。
标签: c algorithm binary-search-tree