所以问题是我无法返回二叉树中的错误语句。
#include <iostream>
#include <string>
using namespace std;
struct Node
{
int Identification;
string full_name;
Node *left;
Node *right;
};
Node *newNode(int id, string name)
{
Node *temp = new Node;
temp->Identification = id;
temp->full_name = name;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* insert(Node* node, int id, string name)
{
if ( node == NULL)
{
return newNode(id,name);
}
if(id < node->Identification)
{
node->left = insert(node->left, id, name);
}
else if (id > node->Identification)
{
node->right = insert(node->right, id, name);
}
return node;
}
bool search(Node* root, int id)
{
if (root == NULL || root->Identification == id)
{
cout << root->full_name << endl;
return true;
}
else if (root != NULL && root->Identification != id)
{
cout << "Record not found";
return false;
}
if (root->Identification < id)
{
return search(root->right, id);
}
return search(root->left, id);
}
int main()
{
int searching;
Node *root = NULL;
root = insert(root, 1021, "John Williams");
root = insert(root, 1057, "Bill Witherspoon");
root = insert(root, 2487, "Jennifer Twain");
root = insert(root, 3769, "Sophia Lancaster");
root = insert(root, 1017, "Debbie Reece");
root = insert(root, 1275, "George McMullen");
root = insert(root, 1899, "Ashley Smith");
root = insert(root, 4218, "Josh Plemmons");
cout << "Enter ID to find employe name ";
cin >> searching;
search(root, searching);
return 0;
}
当我输入 444 并返回
false
, No Id found
时,它会起作用。当我输入 1021 时,它返回 true,
John Williams. But when I use other IDs like for example 1899, which correspond with
Ashley smith, it returns
false`。所以我不知道是什么问题。
函数
search
中,代码
if (root == NULL || root->Identification == id)
{
cout << root->full_name << endl;
return true;
}
没有意义,因为如果
if
块的内容由于 root == NULL
而执行,那么您将通过使用表达式 NULL
取消引用此 root->full_name
指针,这将调用未定义的行为(即可能导致分段错误)。
此外,在该函数中,以下代码无法访问:
if (root->Identification < id)
{
return search(root->right, id);
}
return search(root->left, id);
它是不可到达的,因为前面两个
if
语句的条件都必须评估false
才能达到此代码,但这是不可能的。条件不行
if (root == NULL || root->Identification == id)
和
if (root != NULL && root->Identification != id)
都评估为
false
。如果第一个是true
,第二个将永远是false
。
search
函数应该如下所示:
bool search(Node* root, int id)
{
if ( root == NULL )
{
return false;
}
if ( id < root->Identification )
{
return search( root->left, id );
}
if ( id > root->Identification )
{
return search( root->right, id );
}
return true;
}
现在当您输入
true
时,该功能将返回1899
。