声明新节点但不等于 NULL

Declaring a new node but doesn't equals NULL

本文关键字:不等于 NULL 节点 新节点 声明      更新时间:2023-10-16
class node
{
public:
    int data;
    node *left;
    node *right;
};
void insert(node * root, node * newnode)
{
if (root != NULL)
{
    cout<<"Here1"<<endl;
    if (root->data > newnode->data)
        if (root->left != NULL)
            insert(root->left,newnode);
        else
            root->left = newnode;
    else
        if (root->right != NULL)
            insert(root->right,newnode);
        else
            root->right = newnode;
    return;
}
else
    root = newnode;
}
void inorder(node * root)
{
if (root != NULL)
{
    inorder(root->left);
    cout<<root->data<<endl;
    inorder(root->right);
}
}
node * newn(int ele)
{
    node *newnode = new node();
    newnode->left = NULL;
    newnode->right = NULL;
    newnode->data = ele;
    return newnode;
}
int main(void)
{
int ele,choice = 0;
node *root = new node();
while(choice != 5)
{
    cout<<"1. Entern"
           "2. Inordern"
           "3. PreOrdern"
           "4. PostOrdern"
           "5. Exitn";
    cin>>choice;    
    switch(choice)
    {
        case 1: cout<<"nElement : ";
                cin>>ele;
                insert(root,newn(ele));
                break;
        ....

这是 c++ 中二叉搜索树的代码。它只是插入部分。以及订单打印功能。

当我创建 3 个节点,然后尝试按顺序打印时,它最初显示为零。为了测试这一点,我尝试打印"这里",似乎当我声明根节点指针并且它不等于 NULL 时。我似乎不明白这一点。

insert 函数中,参数root是按值传递的,这意味着指针被复制,在函数内部您只有副本。 更改副本当然不会更改原始副本。

您需要通过引用传递指针:

void insert(node *& root, node * newnode)

如果您花一分钟的调试时间,您自己很容易发现这一点。

我通过将根等同于 NULL 来纠正错误

node *root = new node();
root = NULL;

在初始化时。不需要通过引用传递,因为如果参数是通过引用传递的,它会自动传递指向该函数的指针(引用该对象)。但就我而言,由于我已经传递了一个指针,因此无需通过引用传递指针。