I'm currently playing around with binary trees, but it seems I can't even get my insert function to work correctly. When I try to compile my code, i get the following error:
Code:
Unhandled exception at 0x0121145c in testing.exe: 0xC0000005: Access violation reading location 0xcdcdcdcd.
Here is the code
binTree.h
Code:
#ifndef GUARD_BINTREE
#define GUARD_BINTREE
struct node
{
int data;
node* link[2];
};
class binTree
{
private:
node* root;
public:
binTree(): root(0){}
void insert(int data);
};
void binTree::insert(int data)
{
node* new_node = new node;
new_node->data = data;
//search and insert
if(root == 0)
{
root = new_node;
return;
}
else
{
node* it = root;
int dir;
while(true)
{
dir = it->data < data;
if(it->link[dir] == 0)
break;
else if(it->data == data)
return;
it = it->link[dir];
}
it->link[dir] = new_node;
}
}
#endif
main.cpp
Code:
#include "binTree.h"
int main(int argc, char** argv)
{
binTree tree;
for(int i = 0; i != 10; i++)
tree.insert(i);
return 0;
}
Stepping through with a debugger shows that it is at the location 0xcdcdcdcd. and supposedly happens at
Code:
dir = it->data < data;
Can anyone see what's wrong?
Thanks