在二叉树中搜索
search in a binary tree
我编写了以下函数,用于在存储整数值的二叉树中搜索一个值(该函数是一个较大程序的一部分):
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操作系统。
填上else
,你的问题就会消失。
因为在temp = temp->right;
之后你必须再次检查temp
,但在你的原始代码中,你立即测试temp->data
,这可能不是一个有效的指针。
bool tree::search(int num)
{
node *temp = head;
while (temp != NULL)
{
if (temp->data == num)
break;
if (num > temp->data)
temp = temp->right;
else // <--- Put this 'else' here
if (num < temp->data)
temp = temp->left;
}
if (temp == NULL)
return false;
if (temp->data == num)
return true;
return false;
}
std::set
使用std::set
;它基本上是STL的二叉树。如果你想搜索一些东西,你会使用count
, find
或lower_bound
。
实现基本的数据结构是很好的练习,但在生产中,首先尝试使用STL,因为它们是由具有相关编译器/平台特定知识的专业人员实现的。Boost是另一个很棒的数据结构和常用习惯用法集。
相关文章:
- 从父数组测试用例构造二叉树失败
- 打印时有二叉树问题.用户输入不打印任何内容
- 试图找到二叉树的深度
- 按位置搜索,二叉树C++
- 给定的二叉树是否是二叉搜索树
- 程序设置二叉树,打印和搜索 - 节点类C++
- C++ 在不同类型的二叉树中搜索二叉树
- 我试图证明一个给定的树是一个二进制搜索树.我将输入一个二叉树,我只想让函数返回true
- 二叉树搜索的实现和函数声明c++
- 按键值搜索无序的二叉树
- 二叉树搜索不起作用
- 需要二叉树程序的帮助(不是二叉搜索树)
- 函数用于检查二叉树是否为二叉搜索树或是否工作
- 二叉树搜索没有返回期望的值
- 在对象的二叉树中搜索单个类成员
- 如何创建二叉树(不是二叉搜索树)
- 二叉树搜索不返回结果(c++)
- 二叉树搜索和跟踪
- 在二叉树中搜索
- 基于数据集合执行二叉树搜索