根据用户输入控制插入BST

问题描述 投票:1回答:1

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

      #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()中调用显示函数/命令时,它不显示任何值,并且程序因错误而停止我正在使用循环来接受输入,因此它可以接受高达用户指定值/范围的值但显示/顺序功能不起作用。

我该如何解决此问题?

c++ recursion data-structures binary-tree binary-search-tree
1个回答
1
投票

在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);
}
© www.soinside.com 2019 - 2024. All rights reserved.