[英]Recursive search in binary tree
我是一个初学者,我被困在一个 function 上,它在无序二叉树中搜索给定的键。 节点由值和指向左右节点的指针组成。 这是我的代码:
node *btree::search(int key, node *leaf){
if(leaf != NULL)
{
if(key == leaf->value)
{
return leaf;
}
search(key, leaf->left);
search(key, leaf->right);
}
else
{
return NULL;
}
}
node *btree::search(int key){
return search(key, root);
}
在某些情况下,我的 function 返回正确的节点,但在其他情况下是运行时错误。 这有什么问题,可以做些什么来解决这个问题? 而且我不允许使用任何外部库,例如队列或其他库。
这是一个相当常见的初学者错误。 您的递归 function 返回一个节点指针,但是当您进行递归调用时,您会忽略返回值。
search(key, leaf->left);
search(key, leaf->right);
它应该看起来像这样
node* ptr = search(key, leaf->left);
if (ptr != NULL)
return ptr;
else
return search(key, leaf->right);
即返回通过在左子树中搜索找到的节点,但如果是 NULL 则搜索右子树并返回在那里找到的节点(如果有)。
当您编写递归代码时,您不仅要考虑递归调用,还要考虑递归调用返回的内容。
您调用未定义的行为,因为并非递归函数的所有代码路径都返回一个值。 这可能会导致“运行时错误”、崩溃或只是一些不可预知的结果。
顺便说一句,搜索树的优势通常是您可以获得对元素的平均访问时间,运行时复杂度为 n*log(n)。 但是为此,树必须是有序的,我无法想象无序二叉树的有效用例; 在这种情况下,链表也可以完成这项工作。
如果是有序树:
node *btree::search(int key, node *leaf){
if(leaf != NULL)
{
if(key == leaf->value) {
return leaf;
} else if (key < leaf->value) {
return search(key, leaf->left);
} else {
return search(key, leaf->right);
}
}
else
{
return NULL;
}
}
在无序树的情况下:
node *btree::search(int key, node *leaf){
if(leaf != NULL)
{
if(key == leaf->value) {
return leaf;
}
leaf = search(key, leaf->left);
if (! leaf) {
leaf = search(key, leaf->right);
}
return leaf;
}
else
{
return NULL;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.