使用 void 函数插入二叉搜索树 [英] Binary Search Tree Insertion using a void function

查看:39
本文介绍了使用 void 函数插入二叉搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了两种不同的代码来插入二叉树,一种有效,另一种无效.

I have written two different codes for inserting into a binary tree, one works whereas other doesn't.

这是我的节点的样子:

struct node
{
    int data;
    node *left;
    node *right;
};

以下是node* newnode(int a)

node* newnode(int a)
{
    node *temp=new node;
    temp->data=a;
    temp->left=nullptr;
    temp->right=nullptr;
    return temp;
}

以下是两种不同的插入代码:

And following are the two different codes for insertion:

这个返回一个指向节点的指针:

This one returns a pointer to the node:

 node* insertion(node *root, int a)
 {
    if(root==nullptr)
        return newnode(a);
    else if(a<root->data)
        root->left=insertion(root->left, a);
    else
        root->right=insertion(root->right, a);
 }

这个返回void:

void insertion2(node *root,int a)
{
    if(root==nullptr)
        root=newnode(a);
    else if(a<root->data)
        insertion2(root->left,a);
    else
        insertion2(root->right,a);
}

返回 void 的那个不起作用.根据我的分析,在函数调用之后,root 仍然是 nullptr.谁能解释一下为什么它不起作用?

The one which returns void doesn't work. And as per the analysis I made, after the function call, root is still nullptr. Can anyone explain me why does it not work?

推荐答案

请注意,在 insertion 版本中,您有 root->left = insert(root->left, a)root->right = insert(root->right, a),但是在 insertion2 中没有任何相同的效果.实际上,insertion2 除了泄漏内存之外什么都不做.

Notice that in the insertionversion you have root->left = insertion(root->left, a) and root->right = insertion(root->right, a), but you have nothing to the same effect in insertion2. In effect, insertion2 does nothing except leak memory.

这篇关于使用 void 函数插入二叉搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆