[英]Binary Tree root is null
I'm trying to create a binary search tree but it doesn't seem to be working.我正在尝试创建一个二叉搜索树,但它似乎不起作用。 I debugged it, and it says the root is null.
我调试了它,它说根为空。 I don't understand why it is null.
我不明白为什么它是空的。 I set it to null initially in the constructor, but then when I call the insert() method, it is no longer null, right?
我最初在构造函数中将它设置为 null,但是当我调用 insert() 方法时,它不再为 null,对吗? Can someone help me understand this.
有人可以帮助我理解这一点。 Thanks.
谢谢。
#include "stdafx.h"
#include <iostream>
using namespace std;
struct node
{
public:
int value;
node * left;
node * right;
};
class bTree
{
public:
node * root;
public:
bTree();
void insert(node * r, int val);
void insert(int val);
void traversePreorder();
void traversePreorder(node * r);
};
bTree::bTree()
{
root = NULL;
}
void bTree::insert(node * r, int val)
{
if (r == NULL)
{
r = new node();
r->value = val;
r->left = NULL;
r->right = NULL;
return;
}
else
{
if (val <= r->value)
{
insert(r->left, val);
}
else
{
insert(r->right, val);
}
}
}
void bTree::insert(int val)
{
insert(root, val);
}
void bTree::traversePreorder(node * r)
{
if (root == nullptr)
return;
else
{
cout << root->value << " ";
traversePreorder(root->left);
traversePreorder(root->right);
}
}
void bTree::traversePreorder()
{
traversePreorder(root);
}
int main()
{
bTree * myTree = new bTree();
myTree->insert(30);
myTree->insert(40);
myTree->insert(20);
myTree->insert(10);
myTree->insert(50);
myTree->traversePreorder();
return 0;
}
If you debug into void bTree::insert(node * r, int val)
, you'll find that root
does not get changed at all.如果你调试到
void bTree::insert(node * r, int val)
,你会发现root
根本没有改变。
In void bTree::insert(node * r, int val)
, r
is passed by value, so the change of r
inside the function ( new
etc) has nothing to do with the outside variable ( root
).在
void bTree::insert(node * r, int val)
, r
是按值传递的,因此函数内部r
的变化( new
等)与外部变量( root
)无关。 You could change it to pass by reference:您可以将其更改为通过引用传递:
void bTree::insert(node *& r, int val)
See What's the difference between passing by reference vs. passing by value?请参阅按引用传递与按值传递之间的区别是什么?
How to pass objects to functions in C++?如何将对象传递给 C++ 中的函数?
BTW: In void bTree::traversePreorder(node * r)
, you should use r
, not root
:顺便说一句:在
void bTree::traversePreorder(node * r)
,您应该使用r
,而不是root
:
void bTree::traversePreorder(node * r)
{
if (r == nullptr)
return;
else
{
cout << r->value << " ";
traversePreorder(r->left);
traversePreorder(r->right);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.