【发布时间】:2012-12-27 11:40:53
【问题描述】:
我编写了以下函数来在存储整数值的二叉树中搜索一个值(该函数是更大程序的一部分):
bool tree::search(int num) //the function belongs to class 'tree'
{
node *temp=head; //'head' is pointer to root node
while(temp!=NULL)
{
if(temp->data==num)
break;
if(num>temp->data)
temp=temp->right;
if(num<temp->data)
temp=temp->left;
}
if(temp==NULL)
return false;
else if(temp->data==num)
return true;
}
问题是:当我搜索树中存在的值时,它运行良好。但是如果我搜索树中不存在的值,程序就会挂起,我必须关闭它。 还有一件事-我知道我们可以通过将 node *temp 作为参数传递来递归地实现搜索功能,而不是在内部声明它,我已经这样做了,这导致程序正确运行,但我想知道问题出在哪里在上面的代码中。
我在这里给出完整的程序,以防万一它使查找故障更容易(请注意,我只编写了两个函数):
#include<iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
class tree
{
public:
node *head; //pointer to root
int count; //stores number of elements in tree
tree();
void addnode(int);
void deletenode(int);
bool search(int);
int minimum();
int maximum();
void inorder();
void preorder();
void postorder();
void printtree();
int mthlargest(); //finds 'm'th largest element
int mthsmallest(); //finds 'm'th smallest element
void convert(); //converts binary tree to linked list
};
tree::tree()
{
head=NULL;
count =0;
}
void tree::addnode(int num)
{
node *temp= new node;
temp->data=num;
temp->left=NULL;
temp->right=NULL;
node **ptr=&head; //double pointer
while(*ptr!=NULL)
{
if(num>(*ptr)->data)
ptr=&((*ptr)->right);
if(num<(*ptr)->data)
ptr=&((*ptr)->left);
}
*ptr=temp;
}
bool tree::search(int num)
{
node *temp=head;
while(temp!=NULL)
{
if(temp->data==num)
break;
if(num>temp->data)
temp=temp->right;
if(num<temp->data)
temp=temp->left;
}
if(temp==NULL)
return false;
else if(temp->data==num)
return true;
}
int main()
{
tree ob;
ob.addnode(2);
ob.search(2);
ob.search(3);
ob.search(-1);
ob.search(2);
cout<<endl<<endl;
system("pause");
return 0;
}
旁注:我使用的是 Dev C++ 编译器和 Windows 7 操作系统。
【问题讨论】:
-
你能格式化你的源代码吗?很难阅读。
-
你没有使用
std::set有什么原因吗? -
@Alex :是的,原因是我不知道 std::set 是什么。我是编程初学者。
-
已接受答案中的 else 将起作用,但更好的方法是
temp = (num > temp->data) ? temp->right : temp->left,它允许编译器使用cmov指令。
标签: c++ search binary-search-tree