这是我的二进制搜索树代码:
#include<iostream>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
node* createNode(int value)
{
node* newNode = new node;
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
node* insert( node* root, int data)
{
if (root == NULL) return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(node* root)
{
inorder(root->left);
cout<< root->data<<" ";
inorder(root->right);
}
int main()
{
node *root = NULL;
int n;
cout << "How many values do you want to enter" << endl;
cin >> n;
int no;
for (int i = 0; i < n; i++)
{
cin >> no;
insert(root, no);
}
inorder(root);
}
当我在int main()中调用显示函数/顺序时,它不显示任何值,并且程序因错误而停止
我正在使用循环进行输入,因此它可以将值转换为用户指定的值/范围
但是显示/顺序功能不起作用。
我该如何解决这个问题?
最佳答案
在inOrder函数中,您没有停止条件!
并且主要应该是root=insert(root, no);
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node* left;
struct node* right;
}node;
node* createNode(int value)
{
node* newNode = new node;
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
node* insert( node* root, int data)
{
if (root == NULL) return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(node* root)
{
if(root == NULL)return;
inorder(root->left);
cout<< root->data<<" ";
inorder(root->right);
}
int main()
{
node *root = NULL;
int n;
cout << "How many values do you want to enter" << endl;
cin >> n;
int no;
for (int i = 0; i < n; i++)
{
cin >> no;
root=insert(root, no);
}
inorder(root);
}
关于c++ - 根据用户输入控制插入BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61956455/