声明新节点但不等于 NULL
Declaring a new node but doesn't equals NULL
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;
在初始化时。不需要通过引用传递,因为如果参数是通过引用传递的,它会自动传递指向该函数的指针(引用该对象)。但就我而言,由于我已经传递了一个指针,因此无需通过引用传递指针。
相关文章:
- 为什么 std::round(sin(pi/6)) 不等于 1?
- 为什么在C++中增加指针后打印了一个值而不是 NULL/0?
- 为什么在C++中使用delete后指针不为NULL
- 你怎么编码,如果x不等于一个数字,程序就会退出
- u张量模型输出不等于预期输出
- 虽然不等于陈述和/或差异
- 这种关系不等于定义良好的表达式吗?
- stbi_load() 不返回任何内容,但不返回 null
- OpenGL 版本不等于支持的着色器版本
- 两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?
- 如果整数不等于 0,则将其减小为 1
- C 循环虽然不等于任何两个值
- vb.net单不等于c float
- 如何获取C编译器#Error如果大小(struct ..)不等于给定的数字
- C++ 而语句不等于检查
- 链表:最后一个指针不是NULL
- 有没有办法检查int是否不等于数组中的所有值?(C )
- 整数数组中的元素数量不等于其大小
- 获取不等于特定值的向量的第一个N元素
- 声明新节点但不等于 NULL