在二叉搜索树中搜索对象

时间:2016-06-06 07:57:23

标签: c++ data-structures tree segmentation-fault binary-search-tree

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

  // 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;


 }

1 个答案:

答案 0 :(得分:0)

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

$scope.list=[]
   $scope.x={}
   if($localStorage.list){
     $scope.$storage=$localStorage.list;
     $scope.list=$localStorage.list;
   }
   $scope.add=function(x){
    $scope.list.push(x);
    $scope.$storage= $localStorage.list
    $scope.x={}
  }