我正在为一家公司实施一棵树,我必须将其链接到AVL树进行日志搜索。
AVL树内的搜索功能是:
node* searchNode(string S, node* root) //(S,root)
{
if (root->Name == S)
{
if (root->present == 1)
{
cout<<"root found"<<endl;
cout<<root<<endl;
return root;
}
else
{
cout<<"not found"<<endl;
return NULL;
}
}
else if (S > root->Name)
{
cout<<"search shifted right"<<endl;
searchNode(S, root->right);
}
else
{
cout<<"search shifted left"<<endl;
searchNode(S,root->left);
}
}
另一个功能是:
node* search(string S)
{
cout<<"started search"<<endl;
node *searchResult;
searchResult = companyTree.searchNode(S,companyTree.root);
cout<<searchResult<<endl;
cout<<"finished search"<<endl;
return searchResult;
}
问题在于
cout<<root<<endl;
和
cout<<searchResult<<endl;
不要给出相同的指针地址。此外,当我尝试访问从搜索(S)函数返回的节点的任何元素时,我得到一个分段错误。我该怎么办?
struct节点是:
struct node
{
string Name;
node *left;
node *right;
employee* self;
int present; //1 if present, 0 if absent
node()
{
Name= " ";
left= NULL;
right=NULL;
self=NULL;
present=-1;
}
};
答案 0 :(得分:0)
在递归调用函数的地方添加return。
node* searchNode(string S, node* root) //(S,root)
{
if (root->Name == S)
{
if (root->present == 1)
{
cout<<"root found"<<endl;
cout<<root<<endl;
return root;
}
else
{
cout<<"not found"<<endl;
return NULL;
}
}
else if (S > root->Name)
{
cout<<"search shifted right"<<endl;
return searchNode(S, root->right);
}
else
{
cout<<"search shifted left"<<endl;
return searchNode(S,root->left);
}
希望这有效。