首页 > 解决方案 > 根据用户输入控制插入到 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 时,它不显示任何值,并且程序因错误而停止.

我该如何解决这个问题?

标签: c++recursiondata-structuresbinary-treebinary-search-tree

解决方案


在 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);
}

推荐阅读