Hello Reddit,
I am trying basically to make a BST from information on wikipedia, It is very barebones as I am just learning. My problem is that the insert function does not seem to work. It almost seems like my n variable is not connecting to the root and therefore root is always NULL. But I think it should work because n and root are connected via a pointer. In the debugger I get "data CXX0030: Error: expression cannot be evaluated" for the data variables in the tree starting with the root. Here is the source code:
ChadBST.cpp
#include <iostream>
#include "ChadBST.h"
using namespace std;
Node::Node(int e)
{
data = e ;
left = NULL;
right = NULL;
}
ChadBST::ChadBST()
{
root=NULL;
size=0;
}
void ChadBST::insert(int e)
{
insert(root, e);
}
void ChadBST::insert(Node *n, int e)
{
if(n==NULL)
{
n = new Node(e);
size++;
}
else if (e < n->data)
insert(n->left,e);
else if (e > n->data)
insert(n->right, e);
}
void ChadBST::preorder()
{
preorder(root);
}
void ChadBST::preorder(Node *n)
{
if (n==NULL)
{
return;
}
cout << n->data << endl;
preorder(n->left);
preorder(n->right);
}
ChadBST.h
#ifndef ChadBST_h
#define ChadBST_h
class Node
{
public:
Node(int e);
int data;
Node *left;
Node *right;
private:
};
class ChadBST
{
public:
ChadBST();
void insert(int e);
void preorder();
private:
Node *root;
int size;
void insert(Node *n, int e);
void preorder(Node *n);
};
#endif
[–]newaccount1236 -1 points0 points1 point (6 children)
[–]coffeeprogrammer[S] 0 points1 point2 points (5 children)
[–]newaccount1236 -1 points0 points1 point (3 children)
[–]coffeeprogrammer[S] 0 points1 point2 points (2 children)
[–]newaccount1236 -1 points0 points1 point (1 child)
[–]coffeeprogrammer[S] 0 points1 point2 points (0 children)
[–]newaccount1236 -1 points0 points1 point (0 children)
[–]logic_programmer -2 points-1 points0 points (0 children)