Reputation: 45
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? 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;
}
Upvotes: 2
Views: 2111
Reputation: 172894
If you debug into void bTree::insert(node * r, int val)
, you'll find that root
does not get changed at all.
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
). 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++?
BTW: In void bTree::traversePreorder(node * r)
, you should use r
, not root
:
void bTree::traversePreorder(node * r)
{
if (r == nullptr)
return;
else
{
cout << r->value << " ";
traversePreorder(r->left);
traversePreorder(r->right);
}
}
Upvotes: 2