【发布时间】:2019-05-10 17:22:13
【问题描述】:
我想在不使用父指针的情况下递归且高效地搜索二叉搜索树中的前任。 我将树的根和某些数据(可以包含或不包含在 BST 中)作为函数的参数。
我遇到了麻烦,因为如果 BST 不包含数据,该函数应该在输出中给出小于它的最大值。
Node *recPredecessor(Node *root, int data, Node *pred){
if(root->key > data){
return recPredecessor(root->left, data, pred);
}
if(root->key < data){
return recPredecessor(root->right, data, root);
}
if((root == NULL) || (root->key == data)){
if(root == NULL){
return pred;
}
if(root->key == data){
if(root->left != NULL){
return bstRecGetMax(root->left); //this func return node with Max key
}else{
return pred;
}
}
}
}
【问题讨论】:
-
遍历树的时候,只要保持前任..
-
我忘了说应该递归完成
-
真的没关系。在递归函数中添加一个名为“parent”的参数,并将当前访问的节点作为一个传递。
-
我把我写的代码贴出来了
标签: c binary-search-tree