c++ - 为什么在 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);
}
解决方案
您的代码的问题是,每当您更改函数中的变量nroot
(而不是更改nroot
指向的值)时insert
,这些更改将是insert
函数的本地更改。所以它们不会出现在insert
函数的外部。所以这不是正确的方法。
为此,您可以返回nroot
或使用double pointer
或reference
到节点
推荐阅读
- laravel - file_put_contents(C:\xampp\htdocs\instant\storage\framework/sessions/FF):无法打开流:没有这样的文件或目录
- django - AttributeError:“概述”对象没有属性“__qualname__”
- objective-c - 将 Objective-C typedef 转换为 Swift 枚举后避免“无法静态分配接口类型”
- c++ - 我需要一种机制来允许使用 C++ 运行时在 ANTLR4 中处理包含文件
- python - python pygame蒙版碰撞
- php - Laravel 中的 Symfony\Process 包(用于 python 文件)
- python - 调用 focus_force 时,Tkinter 组合框不起作用
- python - 如何更新亚秒时间序列熊猫数据框中的单元格值
- c# - 仅当不为空时才包含在 where 语句中
- c# - 抱歉,当我使用 C# Blazor 单击链接时,此地址页面上没有显示任何内容