小编Par*_*rth的帖子

在二叉树中搜索

我编写了以下函数来搜索存储整数值的二叉树中的值(该函数是更大程序的一部分):

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;   
}    
Run Code Online (Sandbox Code Playgroud)

问题是:当我搜索树中存在的值时,它运行正常.但是如果我搜索树中不存在的值,程序就会挂起,我必须关闭它.还有一件事 - 我知道我们可以通过传递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(); …
Run Code Online (Sandbox Code Playgroud)

c++ search binary-search-tree

2
推荐指数
1
解决办法
3万
查看次数

标签 统计

binary-search-tree ×1

c++ ×1

search ×1