在二叉搜索树中搜索对象



>**跟踪函数是我用来搜索二叉搜索树的函数,当我在树中搜索某些内容时,它会返回正确的数字顺序,但是当我想查看数字是否存在时,我得到了分段错误**

  // Binary search tree
  #include <stdio.h>
  #include <iostream>
  #include <assert.h>  
  using namespace std;
struct node
{
int data;
node * left;
node * right;
 };
 node * newNode(int data){
    node * newnode = new node();
 newnode -> data = data;
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}

node* Insert (node * root, int data){
if(root == NULL){
root = newNode(data);
}
else if(data <= root-> data){
    root->left = Insert(root->left, data);
}
else{
    root -> right = Insert(root->right, data);
}
return root;
};
int Trace(node* root,int find){
node * searcher = root;
if(searcher->data == find){
    cout << searcher->data << endl;
}
else if(find <= root -> data){
    Trace(searcher->left, find);
    cout << searcher ->data<< endl;
}
else if(find >= root -> data){
    Trace(searcher->right, find);
    cout << searcher ->data << endl;
}
else cout << "not found" << endl;
return searcher-> data;
 };

 int main(){
node * root = NULL;   // creating an empty tree
root = Insert(root, 234234);
root = Insert(root, 2334);
root = Insert(root, 23784);
root = Insert(root, 223);
root = Insert(root, 4244);
root = Insert(root, 673234);
root = Insert(root, 2);
root = Insert(root, 2344);
root = Insert(root, 234);
Trace(root,4244);
return 0;

 }

当您在树中查找不存在的成员时,您最终会到达 NULL 节点。当您尝试评估其数据时,会出现分段错误。您可以通过检查要评估的节点是否有效来避免这种情况。例如,将函数 Trace 更改为:

int Trace(node* root, int find) {
    node * searcher = root;
    if(!searcher) {
        cout << "Node not found" << endl;
        //return something here
    }
    //rest of function stays the same
}

相关内容

  • 没有找到相关文章

最新更新