c++ - 根据用户输入控制插入BST

标签 c++ recursion data-structures binary-tree binary-search-tree

这是我的二进制搜索树代码:

      #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/

相关文章:

c++ - VBA 调试器精度

c++ - 如何将多参数模板传递给宏?

javascript - 递归迭代嵌套对象以更改所有出现的键值

c# - Windows服务递归无限循环,延迟执行同步任务

java - 使用java创建最大堆

c++ - Qt Layout/Widget 交互 - Layouts within Layouts

c++ - 为什么这个模板类不能正常工作?

algorithm - 迭代数独算法

python - sys.getsizeof() 结果与结构大小不太相关

c - 在二叉树中插入元素