c++ - 根据用户输入控制插入到 BST
问题描述
这是我的二叉搜索树代码:
#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() 中调用 display 函数/inorder 时,它不显示任何值,并且程序因错误而停止.
我该如何解决这个问题?
解决方案
在 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);
}
推荐阅读
- java - 自定义 BindingResult 字段错误信息
- python - 使用 pandas 动态导入 EXCEL 表格并将其分配给 Python 中的 DataFrame
- firebase - Firestore 为 noSQL 和 Flutter 复制 SQL 连接
- selenium - Docker 容器上的 Protractor 异步并行测试
- go - 如何导入本地模块golang?
- swift - 在 UICollectionViewCell 中动态添加 UIButtons - Swift
- javascript - React:获取组件子节点之一的 DOM 位置
- python - Rasa 特工在讲完一个故事后停止回应
- r - 如何在 R 中运行回归,同时省略所有包含 0 的行?
- mysql - MySQL UNION - 删除重复条目的好方法