在二叉树中搜索

search in a binary tree

本文关键字:搜索 二叉树      更新时间:2023-10-16

我编写了以下函数,用于在存储整数值的二叉树中搜索一个值(该函数是一个较大程序的一部分):

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, findlower_bound

实现基本的数据结构是很好的练习,但在生产中,首先尝试使用STL,因为它们是由具有相关编译器/平台特定知识的专业人员实现的。Boost是另一个很棒的数据结构和常用习惯用法集。