我正在尝试使用 c++ 编写二叉搜索树,但该程序仅接受 2 个输入并停止

I'm trying to code a binary search tree using c++ but the program takes only 2 inputs and stops

本文关键字:程序 输入 搜索树 c++      更新时间:2023-10-16

注意//,程序停止接受输入,这是主要问题。

root->cand = data;这是完整的代码:

#include <bits/stdc++.h>
using namespace std;
struct node
{
int cand;
node *left;
node *right;
};
class candies
{
node *root;
public:
candies();
int add(int);
int check();
};
candies::candies()
{
root = NULL;
}
int candies::add(int data)
{
if (root == NULL)
{
root->cand = data; //code stops here
root->left = NULL;
root->right = NULL;
}
else
{
node *temp = root;
while (temp != NULL)
{
if (data < temp->cand)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = new node;
temp->cand = data;
temp->left = temp->right = NULL;
}
return 1;
}
int candies::check()
{
node *temp;
temp = root;
int data;
cin >> data;
while (temp != NULL)
{
if (temp->cand == data)
{
cout << "YESn";
return 1;
}
else if (data < temp->cand)
temp = temp->left;
else if (data > temp->cand)
temp = temp->right;
}
cout << "NOn";
return 0;
}
int main()
{
candies c;
int n;
cin >> n;
while (n--)
{
int data;
cin >> data;
c.add(data);
}
c.check();
}

成员函数add无效,而且具有未定义的行为。

在此 if 语句中

if (root == NULL)
{
root->cand = data; //code stops here
root->left = NULL;
root->right = NULL;
}

使用空指针访问内存。

在此其他语句中

else
{
node *temp = root;
while (temp != NULL)
{
if (data < temp->cand)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = new node;
temp->cand = data;
temp->left = temp->right = NULL;
}

创建的节点temp不会添加到树中。所以程序有内存泄漏。

可以按以下方式编写该函数。最好将其返回类型设为void。否则,函数实现中的返回值 1 没有意义。

class candies
{
node *root;
public:
candies();
void add(int);
int check();
};
//...
void candies::add( int data )
{
node **current = &root;
while ( *current != nullptr )
{
if ( data < ( *current )->cand )
{
current = &( *current )->left;
}
else
{
current = &( *current )->right;
}
}
*current = new node { data, nullptr, nullptr };
} 

您首先要检查根是否为 NULL。如果是,则您正在更改其数据。这根本不好,会导致崩溃。

if (root == NULL)
{
root->cand = data; //code stops here

如果根为 NULL,则必须先创建根节点。

if ( root == nullptr ) {
root = new node;
root->cand = data;