首页 > 解决方案 > 为什么在 BST 插入程序中使用 void 不起作用

问题描述

下面是我的 BST 插入代码。我想使用 void 返回类型进行插入,而不是使用 'struct node*' 作为其返回类型的常规方式。我无法在其中找到错误或逻辑错误。有人可以详细解释为什么我的代码不起作用?

#include<iostream>

using namespace std;

struct node
{
    int val;
    node *left, *right;
};

void ins(int key, node *nroot)
{
    if(nroot == NULL)
    {
        node *temp= new node;
        temp->val=key;
        temp->left=NULL;
        temp->right=NULL;
        nroot=temp;
    }
    else if(key > nroot->val)
    {
        ins(key, nroot->right);
    }
    else
    {
        ins(key, nroot->left);
    }
}

void print(node *nroot)
{
    if(nroot!=NULL)
    {
        print(nroot->left);
        cout<<nroot->val;
        print(nroot->right);
    }
}

main()
{
    int n;
    cin>>n;
    node *root= new node;
    int x;
    cin>>x;
    root->left=NULL;
    root->right=NULL;
    root->val=x;
    for(int i=1;i<n;i++)
    {
        cin>>x;
        ins(x, root);
    }
    print(root);
}

标签: c++treebinary-search-tree

解决方案


您的代码的问题是,每当您更改函数中的变量nroot(而不是更改nroot指向的值)时insert,这些更改将是insert函数的本地更改。所以它们不会出现在insert函数的外部。所以这不是正确的方法。

为此,您可以返回nroot或使用double pointerreference到节点


推荐阅读